package app

import (
	"database/sql"
	"time"

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

// UnMarshalGlBalance decodes swagger to first class object
func UnMarshalGlBalance(s *ledger_models.GlBalance) *GlBalance {
	if s.ID == "" {
		s.ID = uuid.New().String()
	}
	closeDate, err0 := time.Parse(dateTimeFormat, s.CloseDate)
	createdDate, err1 := time.Parse(dateTimeFormat, s.CreatedDate)
	lastModifiedDate, err2 := time.Parse(dateTimeFormat, s.LastModifiedDate)
	return &GlBalance{
		ID:               s.ID,
		AccountName:      s.AccountName,
		Amount:           s.Amount,
		CreatedByID:      s.CreatedByID,
		Credits:          s.Credits,
		Debits:           s.Debits,
		Description:      s.Description,
		GlAccountDisplay: s.GLAccountDisplay,
		GlAccountID:      s.GLAccountID,
		LastModifiedByID: s.LastModifiedByID,
		PeriodID:         s.PeriodID,
		Ref:              s.Ref,
		RollupCredits:    s.RollupCredits,
		RollupDebits:     s.RollupDebits,
		Status:           s.Status,
		TenantID:         s.TenantID,
		CloseDate: sql.NullTime{
			Time:  closeDate,
			Valid: err0 == nil,
		},
		CreatedDate: sql.NullTime{
			Time:  createdDate,
			Valid: err1 == nil,
		},
		LastModifiedDate: sql.NullTime{
			Time:  lastModifiedDate,
			Valid: err2 == nil,
		},
	}
}

// MarshalToSwagger encodes first class object
func (obj *GlBalance) MarshalToSwagger() *ledger_models.GlBalance {
	return &ledger_models.GlBalance{
		ID:               obj.ID,
		AccountName:      obj.AccountName,
		Amount:           obj.Amount,
		CloseDate:        obj.CloseDate.Time.Format(dateTimeFormat),
		CreatedByID:      obj.CreatedByID,
		CreatedDate:      obj.CreatedDate.Time.Format(dateTimeFormat),
		Credits:          obj.Credits,
		Debits:           obj.Debits,
		Description:      obj.Description,
		GLAccountDisplay: obj.GlAccountDisplay,
		GLAccountID:      obj.GlAccountID,
		LastModifiedByID: obj.LastModifiedByID,
		LastModifiedDate: obj.LastModifiedDate.Time.Format(dateTimeFormat),
		PeriodID:         obj.PeriodID,
		Ref:              obj.Ref,
		RollupCredits:    obj.RollupCredits,
		RollupDebits:     obj.RollupDebits,
		Status:           obj.Status,
		TenantID:         obj.TenantID,
	}
}
