package app

import (
	"database/sql"
	"time"

	"code.tnxs.net/taxnexus/lib/api/regs/regs_models"
)

// UnMarshalNotebook decodes swagger to first class object
func UnMarshalNotebook(s *regs_models.Notebook) *Notebook {
	createdDate, e0 := time.Parse(dateTimeFormat, s.CreatedDate)
	lastModfiedDate, e1 := time.Parse(dateTimeFormat, s.LastModifiedDate)
	date, e2 := time.Parse(dateFormat, s.Date)
	datestart, e3 := time.Parse(dateFormat, s.DateStart)
	dateend, e4 := time.Parse(dateFormat, s.DateEnd)
	var items []*NotebookItem
	if s.Items != nil {
		items = []*NotebookItem{}
		for _, itm := range s.Items {
			items = append(items, &NotebookItem{
				ID:         itm.ID,
				ItemName:   itm.ItemName,
				Title:      itm.Title,
				NotebookID: itm.NotebookID,
			})
		}
	}
	return &Notebook{
		ID:               s.ID,
		AccountID:        s.AccountID,
		ContactID:        s.ContactID,
		CreatedByID:      s.CreatedByID,
		Description:      s.Description,
		Items:            items,
		LastModifiedByID: s.LastModifiedByID,
		PeriodEndID:      s.PeriodEndID,
		PeriodStartID:    s.PeriodStartID,
		PreparerID:       s.PreparerID,
		TenantID:         s.TenantID,
		Title:            s.Title,
		CreatedDate: sql.NullTime{
			Time:  createdDate,
			Valid: e0 == nil,
		},
		LastModifiedDate: sql.NullTime{
			Time:  lastModfiedDate,
			Valid: e1 == nil,
		},
		Date: sql.NullTime{
			Time:  date,
			Valid: e2 == nil,
		},
		DateStart: sql.NullTime{
			Time:  datestart,
			Valid: e3 == nil,
		},
		DateEnd: sql.NullTime{
			Time:  dateend,
			Valid: e4 == nil,
		},
	}
}

// MarshalToSwagger encodes first class object
func (obj *Notebook) MarshalToSwagger() *regs_models.Notebook {
	var items []*regs_models.NotebookItem
	if obj.Items != nil {
		items = []*regs_models.NotebookItem{}
		for _, itm := range obj.Items {
			items = append(items, &regs_models.NotebookItem{
				ID:         itm.ID,
				ItemName:   itm.ItemName,
				Title:      itm.Title,
				NotebookID: itm.NotebookID,
			})
		}
	}
	return &regs_models.Notebook{
		ID:               obj.ID,
		AccountID:        obj.AccountID,
		ContactID:        obj.ContactID,
		CreatedByID:      obj.CreatedByID,
		CreatedDate:      obj.CreatedDate.Time.Format(dateTimeFormat),
		Date:             obj.Date.Time.Format(dateFormat),
		DateEnd:          obj.DateEnd.Time.Format(dateFormat),
		DateStart:        obj.DateStart.Time.Format(dateFormat),
		Description:      obj.Description,
		Items:            items,
		LastModifiedByID: obj.LastModifiedByID,
		LastModifiedDate: obj.LastModifiedDate.Time.Format(dateTimeFormat),
		PeriodEndID:      obj.PeriodEndID,
		PeriodStartID:    obj.PeriodStartID,
		PreparerID:       obj.PreparerID,
		TenantID:         obj.TenantID,
		Title:            obj.Title,
	}
}
