package client

import (
	"encoding/json"
	"fmt"
	"os"
	"os/signal"
	"time"
	"work-device/conf"
	"work-device/db/model"

	"github.com/aceld/zinx/ziface"
	"github.com/aceld/zinx/zlog"
	"github.com/aceld/zinx/znet"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

// var GClient ziface.IClient

func Connect() {
	client := znet.NewWsClient("127.0.0.1", 9000)

	//添加首次建立链接时的业务
	// client.SetOnConnStart(DoClientConnectedBegin)
	//注册收到服务器消息业务路由

	client.SetOnConnStart(DoClientConnectedBegin)
	client.AddRouter(OPEN_NATIVE_RENDER, &OpenNativeRenderRouter{})

	//启动客户端client
	client.Start()
	// GClient = client

	// close
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, os.Kill)
	sig := <-c
	fmt.Println("===exit===", sig)
}

// 创建连接的时候执行
func DoClientConnectedBegin(conn ziface.IConnection) {
	// 获取配置/发送消息到服务端,注册workdevice
	system := conf.AppConfig.System

	workdevice := &model.WorkDevice{
		Id:               primitive.NewObjectID().Hex(),
		Name:             system.Name,
		NativeRenders:    make([]*model.NativeRender, 0),
		MaxNativeRenders: system.MaxNativeRender,
		QueryFlags:       "wk01",
		CreateTime:       time.Now(),
		UpdateTime:       time.Now(),
		// State:            1,
	}
	data, err := json.Marshal(&workdevice)
	if err != nil {
		zlog.Error(err)
	}

	err = conn.SendMsg(WORK_DEVICE_REGISTER, data)
	fmt.Println(err)
}
