package edge_service

import (
	"encoding/json"
	"io/ioutil"
	"iot_manager_service/config"
	"iot_manager_service/util/logger"
	"net/http"
	"strings"
)

// ForLightControl 灯控相关操作
type ForLightControl struct{}

type ForLightControlReq struct {
	Tenant     string   `json:"tenant"`
	Codes      []string `json:"codes"`
	Recovery   int      `json:"recovery"`
	Brightness int      `json:"brightness"`
	Switchon   int      `json:"switchon"`
	Whole      int      `json:"whole"`
}
type ForLightControlRes struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

// SwitchLightCtr 向边缘云端发送开关灯指令
func (f ForLightControl) SwitchLightCtr(reqData ForLightControlReq) {
	reqData.Whole = 0
	cfg := config.Instance()
	url := cfg.Foreign.IotEdgeUrl + "/lamp/v1/switch"
	method := "POST"
	client := &http.Client{}
	marshal, _ := json.Marshal(reqData)
	req, err := http.NewRequest(method, url, strings.NewReader(string(marshal)))

	if err != nil {
		logger.Logger.Errorf("SwitchLightCtr NewRequest %v", err.Error())
		return
	}
	req.Header.Add("Content-Type", "application/json")
	res, err := client.Do(req)
	if err != nil {
		logger.Logger.Errorf("SwitchLightCtr Do %v", err.Error())
		return
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		logger.Logger.Errorf("SwitchLightCtr ReadAll %v", err.Error())
		return
	}
	var forLightControlRes ForLightControlRes
	err = json.Unmarshal(body, &forLightControlRes)
	if err != nil {
		logger.Logger.Errorf("SwitchLightCtr Unmarshal %v", err.Error())
		return
	}
	if forLightControlRes.Code != 0 {
		logger.Logger.Errorf("SwitchLightCtr forLightControlRes %v", forLightControlRes.Msg)
		return
	}
	return
}
