package devices

import (
	"encoding/json"
	"fmt"
	"server/dao"
	"server/global"
	"server/model/devices"
	"server/utils/protocol"
)

type ProgramService struct {
}

func (ps *ProgramService) CreateProgram(ref devices.ProgramReq) error {
	result := devices.DiscontentJSON{
		Setdiscontent0: devices.SetDisContent{
			Num:     ref.Program.Num,
			Effect:  ref.Program.Effect,
			Speed:   ref.Program.Speed,
			Stay:    ref.Program.Stay,
			Total:   ref.Program.Total,
			Color:   ref.Program.Color,
			Content: ref.Program.Content,
		},
	}

	// 序列化为 JSON 字符串
	jsonBytes, err := json.MarshalIndent(result, "", "  ")
	if err != nil {
		return fmt.Errorf("转换失败: %v", err)
	}

	err = MqttService.Publish(MqttService.GetTopic(ref.DeviceSn, protocol.TopicChanStatus), jsonBytes)
	if err != nil {
		return fmt.Errorf("error updating: %v", err)
	}

	err = global.GVA_DB.Create(&ref.Program).Error
	if err != nil {
		return err
	}
	fmt.Println("Program CreateProgram === ", ref.Program)
	err = global.GVA_DB.Model(dao.Screens{}).Where("sn = ?", ref.DeviceSn).Update("program_id", ref.Program.ID).Error
	if err != nil {
		return err
	}
	return err
}

func (ps *ProgramService) UpdateProgram(ref devices.ProgramReq) error {
	result := devices.DiscontentJSON{
		Setdiscontent0: devices.SetDisContent{
			Num:     ref.Program.Num,
			Effect:  ref.Program.Effect,
			Speed:   ref.Program.Speed,
			Stay:    ref.Program.Stay,
			Total:   ref.Program.Total,
			Color:   ref.Program.Color,
			Content: ref.Program.Content,
		},
	}

	// 序列化为 JSON 字符串
	jsonBytes, err := json.MarshalIndent(result, "", "  ")
	if err != nil {
		return fmt.Errorf("转换失败: %v", err)
	}

	err = MqttService.Publish(MqttService.GetTopic(ref.DeviceSn, protocol.TopicChanStatus), jsonBytes)
	if err != nil {
		return fmt.Errorf("error updating: %v", err)
	}

	return ref.Program.UpdateProgram()
}
