package client

import (
	"time"
)

type Model struct {
	// object unique id
	ID string

	// created event
	IsCreated bool

	// deleted event
	IsDeleted bool

	// updated event
	IsUpdated bool

	// updated time of this object
	LatestUpdatedTime *time.Time
}

func modelFromMap(m map[string]interface{}) *Model {
	createdAtStr := ToString(m["created_at"])
	updatedAtStr := ToString(m["updated_at"])
	deletedAtStr := ToString(m["deleted_at"])
	updatedAt, _ := ToTime(updatedAtStr)

	isCreated := false
	isUpdated := false
	isDeleted := false
	if deletedAtStr != "" {
		isDeleted = true
	} else if createdAtStr == updatedAtStr {
		isCreated = true
	} else {
		isUpdated = true
	}
	return &Model{ID: ToString(m["id"]), LatestUpdatedTime: updatedAt,
		IsCreated: isCreated, IsUpdated: isUpdated, IsDeleted: isDeleted}
}

type Product struct {
	Model
	// product name
	Name string
	// product color
	Color string
}

func ProductFromMap(m map[string]interface{}) *Product {
	return &Product{Model: *modelFromMap(m),
		Name:  ToString(m["name"]),
		Color: ToString(m["color"])}
}

type PriceSchedule struct {
	Model

	// date
	Date time.Time

	// after shift change
	AfterShiftChange bool

	// product list
	PriceScheduleProducts []*PriceScheduleProduct
}

func PriceScheduleFromMap(m map[string]interface{}) (*PriceSchedule, error) {
	date, err := ToTimeFromISO(m["iso_date"])
	if err != nil {
		return nil, err
	}
	return &PriceSchedule{Model: *modelFromMap(m),
		Date:             *date,
		AfterShiftChange: ToBool(m["after_shift_change"])}, nil
}

type PriceScheduleProduct struct {
	// product id
	ProductID string

	// product name
	Name string

	// product color
	Color string

	// product price
	Price float32
}

func PriceScheduleProductFromMap(m map[string]interface{}) *PriceScheduleProduct {
	return &PriceScheduleProduct{
		ProductID: ToString(m["product_id"]),
		Name:      ToString(m["name"]),
		Color:     ToString(m["color"]),
		Price:     ToFloat32(m["price"]),
	}
}

type PriceChangeHistory struct {
	// object unique id of local server
	ID string `json:"id"`

	// original schedule id from FHO
	//
	// omit this id, if price change is done by local server
	PriceScheduleID string `json:"price_schedule_id"`

	// price change time in DATETIME_FROM_ISO_FORMAT
	PriceChangeTime string `json:"price_change_time"`

	// price change status
	Status string `json:"status"`

	// products of price change history
	PriceChangeHistoryProducts []*PriceChangeHistoryProduct `json:"products"`
}

type PriceChangeHistoryProduct struct {
	// local database row id
	ID string `json:"id"`

	// product id
	ProductID string `json:"product_id"`

	// product name
	Name string `json:"name"`

	// product color
	Color string `json:"color"`

	// product price
	Price float32 `json:"price"`
}