package app

import (
	"database/sql"
	"time"

	"code.tnxs.net/taxnexus/lib/api/devops/devops_models"
	"github.com/google/uuid"
)

// UnMarshalTenant decodes swagger to a first class object
func UnMarshalTenant(s *devops_models.Tenant) *Tenant {
	if s.ID == "" {
		s.ID = uuid.New().String()
	}
	databases := []*Database{}
	for _, itm := range s.Databases {
		databases = append(databases, UnMarshalDatabase(itm))
	}
	tenantUsers := []*TenantUser{}
	for _, itm := range s.TenantUsers {
		tenantUsers = append(tenantUsers, UnMarshalTenantUser(itm))
	}
	roles := []*Role{}
	for _, itm := range s.Roles {
		roles = append(roles, UnMarshalRole(itm))
	}
	createdDate, e0 := time.Parse(dateTimeFormat, s.CreatedDate)
	lastModfiedDate, e1 := time.Parse(dateTimeFormat, s.LastModifiedDate)
	return &Tenant{
		ID:               s.ID,
		AccountID:        s.AccountID,
		Active:           s.Active,
		CreatedByID:      s.CreatedByID,
		Databases:        databases,
		LastModifiedByID: s.LastModifiedByID,
		Roles:            roles,
		Status:           s.Status,
		TenantName:       s.TenantName,
		TenantUsers:      tenantUsers,
		Type:             s.Type,
		Version:          s.Version,
		CreatedDate: sql.NullTime{
			Time:  createdDate,
			Valid: e0 == nil,
		},
		LastModifiedDate: sql.NullTime{
			Time:  lastModfiedDate,
			Valid: e1 == nil,
		},
	}
}

// MarshalToSwagger encodes a first class object to swagger
func (obj *Tenant) MarshalToSwagger() *devops_models.Tenant {
	databases := []*devops_models.Database{}
	for _, itm := range obj.Databases {
		databases = append(databases, itm.MarshalToSwagger())
	}
	tenantUsers := []*devops_models.TenantUser{}
	for _, itm := range obj.TenantUsers {
		tenantUsers = append(tenantUsers, itm.MarshalToSwagger())
	}
	roles := []*devops_models.Role{}
	for _, itm := range obj.Roles {
		roles = append(roles, itm.MarshalToSwagger())
	}
	return &devops_models.Tenant{
		ID:               obj.ID,
		AccountID:        obj.AccountID,
		Active:           obj.Active,
		CreatedByID:      obj.CreatedByID,
		CreatedDate:      obj.CreatedDate.Time.Format(dateTimeFormat),
		Databases:        databases,
		LastModifiedByID: obj.LastModifiedByID,
		LastModifiedDate: obj.LastModifiedDate.Time.Format(dateTimeFormat),
		Status:           obj.Status,
		TenantName:       obj.TenantName,
		TenantUsers:      tenantUsers,
		Roles:            roles,
		Type:             obj.Type,
		Version:          obj.Version,
	}
}
