package app

import (
	"database/sql"
	"time"

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

// UnMarshalEft decodes swagger to a first class object
func UnMarshalEft(s *ops_models.Eft) *Eft {
	if s.ID == "" {
		s.ID = uuid.New().String()
	}
	items := []*EftItem{}
	for _, itm := range s.Items {
		items = append(items, UnMarshalEftItem(itm))
	}
	createdDate, e0 := time.Parse(dateTimeFormat, s.CreatedDate)
	lastModfiedDate, e1 := time.Parse(dateTimeFormat, s.LastModifiedDate)
	journalDate, e2 := time.Parse(dateTimeFormat, s.JournalDate)
	executed, e3 := time.Parse(dateTimeFormat, s.Executed)
	return &Eft{
		ID:               s.ID,
		AccountID:        s.AccountID,
		Amount:           s.Amount,
		AttemptNumber:    s.AttemptNumber,
		BackendID:        s.BackendID,
		BillingRunID:     s.BillingRunID,
		CashReceiptID:    s.CashReceiptID,
		CreatedByID:      s.CreatedByID,
		Fee:              s.Fee,
		Gateway:          s.Gateway,
		GatewayKey:       s.GatewayKey,
		GatewayMessage:   s.GatewayMessage,
		Items:            items,
		LastModifiedByID: s.LastModifiedByID,
		PaymentMethodID:  s.PaymentMethodID,
		ParentFK:         s.ParentFK,
		Ref:              s.Ref,
		Status:           s.Status,
		TenantID:         s.TenantID,
		TransactionID:    s.TransactionID,
		CreatedDate: sql.NullTime{
			Time:  createdDate,
			Valid: e0 == nil,
		},
		LastModifiedDate: sql.NullTime{
			Time:  lastModfiedDate,
			Valid: e1 == nil,
		},
		JournalDate: sql.NullTime{
			Time:  journalDate,
			Valid: e2 == nil,
		},
		Executed: sql.NullTime{
			Time:  executed,
			Valid: e3 == nil,
		},
	}
}

// MarshalToSwagger encodes a first class object to swagger
func (obj *Eft) MarshalToSwagger() *ops_models.Eft {
	items := []*ops_models.EftItem{}
	for _, itm := range obj.Items {
		items = append(items, itm.MarshalToSwagger())
	}
	return &ops_models.Eft{
		ID:               obj.ID,
		AccountID:        obj.AccountID,
		Amount:           obj.Amount,
		AttemptNumber:    obj.AttemptNumber,
		BackendID:        obj.BackendID,
		BillingRunID:     obj.BillingRunID,
		CashReceiptID:    obj.CashReceiptID,
		CreatedByID:      obj.CreatedByID,
		CreatedDate:      obj.CreatedDate.Time.Format(dateTimeFormat),
		Executed:         obj.Executed.Time.Format(dateTimeFormat),
		Fee:              obj.Fee,
		Gateway:          obj.Gateway,
		GatewayKey:       obj.GatewayKey,
		GatewayMessage:   obj.GatewayMessage,
		Items:            items,
		JournalDate:      obj.JournalDate.Time.Format(dateTimeFormat),
		LastModifiedByID: obj.LastModifiedByID,
		LastModifiedDate: obj.LastModifiedDate.Time.Format(dateTimeFormat),
		PaymentMethodID:  obj.PaymentMethodID,
		ParentFK:         obj.ParentFK,
		Ref:              obj.Ref,
		Status:           obj.Status,
		TenantID:         obj.TenantID,
		TransactionID:    obj.TransactionID,
	}
}
