package app

import (
	"database/sql"
	"time"

	"code.tnxs.net/taxnexus/lib/api/ledger/ledger_models"
	"github.com/google/uuid"
)

// UnMarshalAccountingRule decodes swagger to first class object
func UnMarshalAccountingRule(s *ledger_models.AccountingRule) *AccountingRule {
	if s.ID == "" {
		s.ID = uuid.New().String()
	}
	createdDate, e0 := time.Parse(dateTimeFormat, s.CreatedDate)
	lastModfiedDate, e1 := time.Parse(dateTimeFormat, s.LastModifiedDate)
	return &AccountingRule{
		ID:                   s.ID,
		AccountID:            s.AcountID,
		Code:                 s.Code,
		COGSaccountID:        s.COGSAccountID,
		COGSaccountName:      s.COGSAccountName,
		CreatedByID:          s.CreatedByID,
		CreditAccountID:      s.CreditAccountID,
		CreditAccountName:    s.CreditAccountName,
		DebitAccountID:       s.DebitAccountID,
		DebitAccountName:     s.DebitAccountName,
		Description:          s.Description,
		InventoryAccountID:   s.InventoryAccountID,
		InventoryAccountName: s.InventoryAccountName,
		IsDeferred:           s.IsDeferred,
		LastModifiedByID:     s.LastModifiedByID,
		ParentFK:             s.ParentFK,
		Proportion:           s.Proportion,
		TenantID:             s.TenantID,
		CreatedDate: sql.NullTime{
			Time:  createdDate,
			Valid: e0 == nil,
		},
		LastModifiedDate: sql.NullTime{
			Time:  lastModfiedDate,
			Valid: e1 == nil,
		},
	}
}

// MarshalToSwagger encodes first class object
func (obj *AccountingRule) MarshalToSwagger() *ledger_models.AccountingRule {
	return &ledger_models.AccountingRule{
		ID:                   obj.ID,
		AcountID:             obj.AccountID,
		Code:                 obj.Code,
		COGSAccountID:        obj.COGSaccountID,
		COGSAccountName:      obj.COGSaccountName,
		CreatedByID:          obj.CreatedByID,
		CreatedDate:          obj.CreatedDate.Time.Format(dateTimeFormat),
		CreditAccountID:      obj.CreditAccountID,
		CreditAccountName:    obj.CreditAccountName,
		DebitAccountID:       obj.DebitAccountID,
		DebitAccountName:     obj.DebitAccountName,
		Description:          obj.Description,
		InventoryAccountID:   obj.InventoryAccountID,
		InventoryAccountName: obj.InventoryAccountName,
		IsDeferred:           obj.IsDeferred,
		LastModifiedByID:     obj.LastModifiedByID,
		LastModifiedDate:     obj.LastModifiedDate.Time.Format(dateTimeFormat),
		ParentFK:             obj.ParentFK,
		Proportion:           obj.Proportion,
		TenantID:             obj.TenantID,
	}
}
