package edge_service

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"iot_manager_service/config"
	"net/http"
)

// ForVidiconService  安防service
type ForVidiconService struct {
}

// VidiconRespose 返回respose结构体
type VidiconRespose struct {
	Code int
	Msg  string
}

// Operate 操作球机
func (f *ForVidiconService) Operate(code string, name string, direction int, speed int) (bool, error) {
	cfg := config.Instance()
	api := cfg.Foreign.IotEdgeUrl + "/camera/v1/control/ptz"
	url := fmt.Sprintf("%v?code=%v&direction=%d&speed=%d", api, code, direction, speed)
	return f.getVidiconApi(url)
}

// Ptzhome 复位相关
func (f *ForVidiconService) Ptzhome(code string, name string, flag int) (bool, error) {
	cfg := config.Instance()
	api := cfg.Foreign.IotEdgeUrl + "/camera/v1/control/ptzhome"
	url := fmt.Sprintf("%v?code=%v&flag=%d", api, code, flag)
	return f.getVidiconApi(url)
}

// getVidiconApi 公用请求接口
func (f *ForVidiconService) getVidiconApi(url string) (bool, error) {
	//fmt.Printf("url = %v", url)
	method := "GET"
	client := &http.Client{}
	req, err := http.NewRequest(method, url, nil)
	if err != nil {
		return false, err
	}
	res, err := client.Do(req)
	if err != nil {
		return false, err
	}
	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return false, err
	}
	//fmt.Printf("body = %v", string(body))
	result := VidiconRespose{}
	err = json.Unmarshal(body, &result)
	if err != nil {
		return false, err
	}
	if result.Code != 0 {
		panic(result.Msg)
	}
	return true, nil
}
