package app

import (
	"database/sql"
	"reflect"
	"time"

	"code.tnxs.net/taxnexus/lib/api/crm/crm_models"
	"github.com/google/uuid"
)

// ReMarshalLead converts microservice Models object to swagger
func ReMarshalLead(p interface{}) crm_models.Lead {
	// reflect input and set to crm_models type
	t := reflect.ValueOf(&p).Elem()
	s := crm_models.Lead{}
	r := reflect.ValueOf(&s).Elem()
	for i := 0; i < t.NumField(); i++ {
		r.Field(i).Set(t.Field(i))
	}
	return s
}

// UnMarshalLead decodes swagger to first class object
func UnMarshalLead(s *crm_models.Lead) *Lead {
	if s.ID == "" {
		s.ID = uuid.New().String()
	}
	createdDate, e0 := time.Parse(dateTimeFormat, s.CreatedDate)
	lastModfiedDate, e1 := time.Parse(dateTimeFormat, s.LastModifiedDate)
	return &Lead{
		ID:               s.ID,
		Address:          UnMarshalCrmAddress(s.Address),
		Company:          s.Company,
		Description:      s.Description,
		Email:            s.Email,
		FirstName:        s.FirstName,
		LastName:         s.LastName,
		MobilePhone:      s.MobilePhone,
		Name:             s.Name,
		OwnerID:          s.OwnerID,
		PartnerAccountID: s.PartnerAccountID,
		Phone:            s.Phone,
		ProductID:        s.ProductID,
		RefererURL:       s.RefererURL,
		Status:           s.Status,
		Title:            s.Title,
		Type:             s.Type,
		UTMCampaign:      s.UTMCampaign,
		UTMContent:       s.UTMContent,
		UTMMedium:        s.UTMMedium,
		UTMSource:        s.UTMSource,
		UTMTerm:          s.UTMTerm,
		Website:          s.Website,
		CreatedByID:      s.CreatedByID,
		LastModifiedByID: s.LastModifiedByID,
		TenantID:         s.TenantID,
		CreatedDate: sql.NullTime{
			Time:  createdDate,
			Valid: e0 == nil,
		},
		LastModifiedDate: sql.NullTime{
			Time:  lastModfiedDate,
			Valid: e1 == nil,
		},
	}
}

// MarshalToSwagger encodes first class object
func (obj *Lead) MarshalToSwagger() *crm_models.Lead {
	return &crm_models.Lead{
		ID:               obj.ID,
		Address:          obj.Address.MarshalToCrm(),
		Company:          obj.Company,
		CreatedByID:      obj.CreatedByID,
		CreatedDate:      obj.CreatedDate.Time.Format(dateTimeFormat),
		Description:      obj.Description,
		Email:            obj.Email,
		FirstName:        obj.FirstName,
		LastName:         obj.LastName,
		LastModifiedByID: obj.LastModifiedByID,
		LastModifiedDate: obj.LastModifiedDate.Time.Format(dateTimeFormat),
		MobilePhone:      obj.MobilePhone,
		Name:             obj.Name,
		OwnerID:          obj.OwnerID,
		PartnerAccountID: obj.PartnerAccountID,
		Phone:            obj.Phone,
		ProductID:        obj.ProductID,
		RefererURL:       obj.RefererURL,
		Status:           obj.Status,
		TenantID:         obj.TenantID,
		Title:            obj.Title,
		Type:             obj.Type,
		UTMCampaign:      obj.UTMCampaign,
		UTMContent:       obj.UTMContent,
		UTMMedium:        obj.UTMMedium,
		UTMSource:        obj.UTMSource,
		UTMTerm:          obj.UTMTerm,
		Website:          obj.Website,
	}
}
