package app

import (
	"database/sql"
	"time"

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

func UnMarshalJournalItem(s *ledger_models.JournalItem) *JournalItem {
	if s.ID == "" {
		s.ID = uuid.New().String()
	}
	createdDate, err1 := time.Parse(dateTimeFormat, s.CreatedDate)
	lastModifiedDate, err2 := time.Parse(dateTimeFormat, s.LastModifiedDate)
	return &JournalItem{
		ID:                  s.ID,
		CreatedByID:         s.CreatedByID,
		Credit:              s.Credit,
		Debit:               s.Debit,
		GlAccountID:         s.GLAccountID,
		GlAccountDisplay:    s.GLAccountDisplay,
		GlBalance:           s.GLBalanceID,
		InvoiceItemID:       s.InvoiceItemID,
		JournalEntryID:      s.JournalEntryID,
		LastModifiedByID:    s.LastModifiedByID,
		PoItemID:            s.POItemID,
		ProductCode:         s.ProducCode,
		ProductID:           s.ProductID,
		ReferenceType:       s.ReferenceType,
		SalesRegulation:     s.SalesRegulation,
		TaxnexusCodeID:      s.TaxnexusCodeID,
		TaxnexusCodeDisplay: s.TaxnexusCodeDisplay,
		TaxTransactionID:    s.TaxTransactionID,
		TenantID:            s.TenantID,
		CreatedDate: sql.NullTime{
			Time:  createdDate,
			Valid: err1 == nil,
		},
		LastModifiedDate: sql.NullTime{
			Time:  lastModifiedDate,
			Valid: err2 == nil,
		},
	}
}

// MarshalToSwagger encodes first class object
func (obj *JournalItem) MarshalToSwagger() *ledger_models.JournalItem {
	return &ledger_models.JournalItem{
		ID:                  obj.ID,
		CreatedByID:         obj.CreatedByID,
		CreatedDate:         obj.CreatedDate.Time.Format(dateTimeFormat),
		Credit:              obj.Credit,
		Debit:               obj.Debit,
		GLAccountDisplay:    obj.GlAccountDisplay,
		GLAccountID:         obj.GlAccountID,
		GLBalanceID:         obj.GlBalance,
		InvoiceItemID:       obj.InvoiceItemID,
		JournalEntryID:      obj.JournalEntryID,
		LastModifiedByID:    obj.LastModifiedByID,
		LastModifiedDate:    obj.LastModifiedDate.Time.Format(dateTimeFormat),
		POItemID:            obj.PoItemID,
		ProducCode:          obj.ProductCode,
		ProductID:           obj.ProductID,
		ReferenceType:       obj.ReferenceType,
		SalesRegulation:     obj.SalesRegulation,
		TaxnexusCodeDisplay: obj.TaxnexusCodeDisplay,
		TaxnexusCodeID:      obj.TaxnexusCodeID,
		TaxTransactionID:    obj.TaxTransactionID,
		TenantID:            obj.TenantID,
	}
}
