package app

import (
	"database/sql"
	"time"

	"code.tnxs.net/taxnexus/lib/api/regs/regs_models"
	"github.com/google/uuid"
)

// UnMarshalLicenseType decodes swagger to first class object
func UnMarshalLicenseType(s *regs_models.LicenseType) *LicenseType {
	if s.ID == "" {
		s.ID = uuid.New().String()
	}
	var jurisdictions []*GeoLicenseTypeInstance
	if s.Jurisdictions != nil {
		jurisdictions = []*GeoLicenseTypeInstance{}
		for _, itm := range s.Jurisdictions {
			jurisdictions = append(jurisdictions, &GeoLicenseTypeInstance{
				CountryID:  itm.CountryID,
				CountyID:   itm.CountyID,
				ObjectType: itm.ObjectType,
				PlaceID:    itm.PlaceID,
				StateID:    itm.StateID,
			})
		}
	}
	createdDate, e0 := time.Parse(dateTimeFormat, s.CreatedDate)
	lastModfiedDate, e1 := time.Parse(dateTimeFormat, s.LastModifiedDate)
	return &LicenseType{
		ID:               s.ID,
		AccountID:        s.AccountID,
		AgentID:          s.AgentID,
		ContactID:        s.ContactID,
		Cost:             s.Cost,
		CreatedByID:      s.CreatedByID,
		DomainID:         s.DomainID,
		Domains:          s.Domains,
		Frequency:        s.Frequency,
		Jurisdictions:    jurisdictions,
		LastModifiedByID: s.LastModifiedByID,
		Level:            s.Level,
		MetrcName:        s.MetrcName,
		Name:             s.Name,
		PicklistValue:    s.PicklistValue,
		Ref:              s.Ref,
		Restriction:      s.Restriction,
		Tier:             s.Tier,
		CreatedDate: sql.NullTime{
			Time:  createdDate,
			Valid: e0 == nil,
		},
		LastModifiedDate: sql.NullTime{
			Time:  lastModfiedDate,
			Valid: e1 == nil,
		},
	}
}

// MarshalToSwagger encodes first class object
func (obj *LicenseType) MarshalToSwagger() *regs_models.LicenseType {
	var jurisdictions []*regs_models.GeoLicenseTypeInstance
	if obj.Jurisdictions != nil {
		jurisdictions = []*regs_models.GeoLicenseTypeInstance{}
		for _, itm := range obj.Jurisdictions {
			jurisdictions = append(jurisdictions, &regs_models.GeoLicenseTypeInstance{
				CountryID:  itm.CountryID,
				CountyID:   itm.CountyID,
				ObjectType: itm.ObjectType,
				PlaceID:    itm.PlaceID,
				StateID:    itm.StateID,
			})
		}
	}
	return &regs_models.LicenseType{
		ID:               obj.ID,
		AccountID:        obj.AccountID,
		AgentID:          obj.AgentID,
		ContactID:        obj.ContactID,
		Cost:             obj.Cost,
		CreatedByID:      obj.CreatedByID,
		CreatedDate:      obj.CreatedDate.Time.Format(dateTimeFormat),
		DomainID:         obj.DomainID,
		Domains:          obj.Domains,
		Frequency:        obj.Frequency,
		Jurisdictions:    jurisdictions,
		LastModifiedByID: obj.LastModifiedByID,
		LastModifiedDate: obj.LastModifiedDate.Time.Format(dateTimeFormat),
		Level:            obj.Level,
		MetrcName:        obj.MetrcName,
		Name:             obj.Name,
		PicklistValue:    obj.PicklistValue,
		Ref:              obj.Ref,
		Restriction:      obj.Restriction,
		Tier:             obj.Tier,
	}
}
