package app

import (
	"database/sql"
	"time"

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

// UnMarshalPeriod decodes swagger to first class object
func UnMarshalPeriod(s *ledger_models.Period) *Period {
	if s.ID == "" {
		s.ID = uuid.New().String()
	}
	createdDate, err1 := time.Parse(dateTimeFormat, s.CreatedDate)
	lastModifiedDate, err2 := time.Parse(dateTimeFormat, s.LastModifiedDate)
	startTime, err3 := time.Parse(dateFormat, s.StartDate)
	endTime, err4 := time.Parse(dateFormat, s.EndDate)
	return &Period{
		ID:               s.ID,
		AccountID:        s.AccountID,
		CompanyID:        s.CompanyID,
		Ref:              s.Ref,
		Days:             s.Days,
		EndDate:          s.EndDate,
		Month:            s.Month,
		Name:             s.Name,
		Quarter:          s.Quarter,
		Semiannual:       s.Semiannual,
		StartDate:        s.StartDate,
		Status:           s.Status,
		TenantID:         s.TenantID,
		Year:             s.Year,
		CreatedByID:      s.CreatedByID,
		LastModifiedByID: s.LastModifiedByID,
		CreatedDate: sql.NullTime{
			Time:  createdDate,
			Valid: err1 == nil,
		},
		LastModifiedDate: sql.NullTime{
			Time:  lastModifiedDate,
			Valid: err2 == nil,
		},
		EndTime: sql.NullTime{
			Time:  endTime,
			Valid: err3 == nil,
		},
		StartTime: sql.NullTime{
			Time:  startTime,
			Valid: err4 == nil,
		},
	}
}

// MarshalToSwagger encodes first class object
func (obj *Period) MarshalToSwagger() *ledger_models.Period {
	return &ledger_models.Period{
		ID:               obj.ID,
		AccountID:        obj.AccountID,
		CompanyID:        obj.CompanyID,
		CreatedByID:      obj.CreatedByID,
		CreatedDate:      obj.CreatedDate.Time.Format(dateTimeFormat),
		Days:             obj.Days,
		EndDate:          obj.EndDate,
		LastModifiedByID: obj.LastModifiedByID,
		LastModifiedDate: obj.LastModifiedDate.Time.Format(dateTimeFormat),
		Month:            obj.Month,
		Name:             obj.Name,
		Quarter:          obj.Quarter,
		Ref:              obj.Ref,
		Semiannual:       obj.Semiannual,
		StartDate:        obj.StartDate,
		Status:           obj.Status,
		TenantID:         obj.TenantID,
		Year:             obj.Year,
	}
}
