package app

import (
	"database/sql"
	"time"

	"code.tnxs.net/taxnexus/lib/api/ops/ops_models"
	"github.com/google/uuid"
)

// UnMarshalCharge decodes swagger to a first class object
func UnMarshalCharge(s *ops_models.Charge) *Charge {
	if s.ID == "" {
		s.ID = uuid.New().String()
	}
	createdDate, e0 := time.Parse(dateTimeFormat, s.CreatedDate)
	lastModfiedDate, e1 := time.Parse(dateTimeFormat, s.LastModifiedDate)
	journalDate, e2 := time.Parse(dateTimeFormat, s.JournalDate)
	return &Charge{
		ID:                    s.ID,
		AccountID:             s.AccountID,
		Amount:                s.Amount,
		BillingContactID:      s.BillingContactID,
		ContractID:            s.ContractID,
		CreatedByID:           s.CreatedByID,
		Description:           s.Description,
		EmailMessage:          s.EmailMessage,
		LastModifiedByID:      s.LastModifiedByID,
		PartnerAccountID:      s.PartnerAccountID,
		PaymentTerms:          s.PaymentTerms,
		PeriodID:              s.PeriodID,
		Posted:                s.Posted,
		ProductID:             s.ProductID,
		Quantity:              s.Quantity,
		TenantID:              s.TenantID,
		UnitPrice:             s.UnitPrice,
		AccountingRulesetCode: s.AccountingRulesetCode,
		BillingEmail:          s.BillingEmail,
		BillingRunID:          s.BillingRunID,
		ContractHourlyRate:    s.ContractHourlyRate,
		Ref:                   s.Ref,
		TemplateID:            s.TemplateID,
		Type:                  s.Type,
		CreatedDate: sql.NullTime{
			Time:  createdDate,
			Valid: e0 == nil,
		},
		LastModifiedDate: sql.NullTime{
			Time:  lastModfiedDate,
			Valid: e1 == nil,
		},
		JournalDate: sql.NullTime{
			Time:  journalDate,
			Valid: e2 == nil,
		},
	}
}

// MarshalToSwagger encodes a first class object to swagger
func (obj *Charge) MarshalToSwagger() *ops_models.Charge {
	return &ops_models.Charge{
		ID:                    obj.ID,
		AccountID:             obj.AccountID,
		Amount:                obj.Amount,
		BillingContactID:      obj.BillingContactID,
		ContractID:            obj.ContractID,
		CreatedByID:           obj.CreatedByID,
		CreatedDate:           obj.CreatedDate.Time.Format(dateTimeFormat),
		Description:           obj.Description,
		EmailMessage:          obj.EmailMessage,
		JournalDate:           obj.JournalDate.Time.Format(dateTimeFormat),
		LastModifiedByID:      obj.LastModifiedByID,
		LastModifiedDate:      obj.LastModifiedDate.Time.Format(dateTimeFormat),
		PartnerAccountID:      obj.PartnerAccountID,
		PaymentTerms:          obj.PaymentTerms,
		PeriodID:              obj.PeriodID,
		Posted:                obj.Posted,
		ProductID:             obj.ProductID,
		Quantity:              obj.Quantity,
		TenantID:              obj.TenantID,
		UnitPrice:             obj.UnitPrice,
		AccountingRulesetCode: obj.AccountingRulesetCode,
		BillingEmail:          obj.BillingEmail,
		BillingRunID:          obj.BillingRunID,
		ContractHourlyRate:    obj.ContractHourlyRate,
		Ref:                   obj.Ref,
	}
}
