package app

import (
	"database/sql"
	"time"

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

// UnMarshalLicense decodes swagger to first class object
func UnMarshalLicense(s *regs_models.License) *License {
	if s.ID == "" {
		s.ID = uuid.New().String()
	}
	createdDate, e0 := time.Parse(dateTimeFormat, s.CreatedDate)
	lastModfiedDate, e1 := time.Parse(dateTimeFormat, s.LastModifiedDate)
	expirationDate, e2 := time.Parse(dateFormat, s.ExpirationDate)
	if e2 != nil {
		expirationDate, e2 = time.Parse(dateFormatAlt, s.ExpirationDate)
	}
	dateIssued, e3 := time.Parse(dateFormat, s.DateIssued)
	if e3 != nil {
		dateIssued, e3 = time.Parse(dateFormatAlt, s.DateIssued)
	}
	return &License{
		ID:               s.ID,
		AccountID:        s.AccountID,
		BackendID:        s.BackendID,
		ContactID:        s.ContactID,
		CreatedByID:      s.CreatedByID,
		Designation:      s.Designation,
		IsCanceled:       s.IsCanceled,
		IsRevoked:        s.IsRevoked,
		LastModifiedByID: s.LastModifiedByID,
		LicenseNumber:    s.Name,
		LicenseTypeID:    s.LicenseTypeID,
		OwnerID:          s.OwnerID,
		ParentFK:         s.ParentFK,
		Ref:              s.Ref,
		Status:           s.Status,
		TenantID:         s.TenantID,
		CreatedDate: sql.NullTime{
			Time:  createdDate,
			Valid: e0 == nil,
		},
		LastModifiedDate: sql.NullTime{
			Time:  lastModfiedDate,
			Valid: e1 == nil,
		},
		ExpirationDate: sql.NullTime{
			Time:  expirationDate,
			Valid: e2 == nil,
		},
		DateIssued: sql.NullTime{
			Time:  dateIssued,
			Valid: e3 == nil,
		},
	}
}

// MarshalToSwagger encodes first class object
func (obj *License) MarshalToSwagger() *regs_models.License {
	return &regs_models.License{
		ID:               obj.ID,
		AccountID:        obj.AccountID,
		BackendID:        obj.BackendID,
		ContactID:        obj.ContactID,
		CreatedByID:      obj.CreatedByID,
		CreatedDate:      obj.CreatedDate.Time.Format(dateTimeFormat),
		DateIssued:       obj.DateIssued.Time.Format(dateFormat),
		Designation:      obj.Designation,
		ExpirationDate:   obj.ExpirationDate.Time.Format(dateFormat),
		IsCanceled:       obj.IsCanceled,
		IsRevoked:        obj.IsRevoked,
		LastModifiedByID: obj.LastModifiedByID,
		LastModifiedDate: obj.LastModifiedDate.Time.Format(dateTimeFormat),
		LicenseTypeID:    obj.LicenseTypeID,
		Name:             obj.LicenseNumber,
		OwnerID:          obj.OwnerID,
		ParentFK:         obj.ParentFK,
		Ref:              obj.Ref,
		Status:           obj.Status,
		TenantID:         obj.TenantID,
	}
}
