package app

import (
	"database/sql"
	"time"

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

// UnMarshalAccountingRuleset decodes swagger to first class object
func UnMarshalAccountingRuleset(s *ledger_models.AccountingRuleset) *AccountingRuleset {
	if s.ID == "" {
		s.ID = uuid.New().String()
	}
	createdDate, e0 := time.Parse(dateTimeFormat, s.CreatedDate)
	lastModfiedDate, e1 := time.Parse(dateTimeFormat, s.LastModifiedDate)
	theItems := []*AccountingRulesetItem{}
	for _, itm := range s.Items {
		theItems = append(theItems, &AccountingRulesetItem{
			ID:                 itm.ID,
			AccountingRuleCode: itm.AccountingRuleCode,
		})
	}
	return &AccountingRuleset{
		ID:          s.ID,
		AccountID:   s.AccountID,
		Code:        s.Code,
		Description: s.Description,
		Items:       theItems,
		CreatedDate: sql.NullTime{
			Time:  createdDate,
			Valid: e0 == nil,
		},
		LastModifiedDate: sql.NullTime{
			Time:  lastModfiedDate,
			Valid: e1 == nil,
		},
	}
}

// MarshalToSwagger encodes first class object
func (obj *AccountingRuleset) MarshalToSwagger() *ledger_models.AccountingRuleset {
	theItems := []*ledger_models.AccountingRulesetItem{}
	for _, itm := range obj.Items {
		theItems = append(theItems,
			&ledger_models.AccountingRulesetItem{
				ID:                 itm.ID,
				AccountingRuleCode: itm.AccountingRuleCode,
				TenantID:           itm.TenantID,
			})
	}
	return &ledger_models.AccountingRuleset{
		ID:               obj.ID,
		AccountID:        obj.AccountID,
		Code:             obj.Code,
		CreatedByID:      obj.CreatedByID,
		CreatedDate:      obj.CreatedDate.Time.Format(dateTimeFormat),
		Description:      obj.Description,
		Items:            theItems,
		LastModifiedByID: obj.LastModifiedByID,
		LastModifiedDate: obj.LastModifiedDate.Time.Format(dateTimeFormat),
		TenantID:         obj.TenantID,
	}
}
