package lc

import (
	"github.com/sirupsen/logrus"
	"lc-smartX/util"
	"net"
	"time"
)

type CorrectTimer interface {
	Correct()
}

func DoCorrectTime(a any) {
	if c, ok := a.(CorrectTimer); ok {
		c.Correct()
	}
}

// IDevice 抽象设备,包含屏和喇叭
type IDevice interface {
	// Call 通知输出设备,输出信息。屏显示来车警告信息，扬声器语音提示
	Call()
	// Back 屏显示原来的无车提醒信息
	Back()
	ReConnect()
	// Correct time 校时
	CorrectTimer
}

type IntersectionDevice struct {
	Info util.OutputDevice
	S    Screen
	L    IpCast
}

func (id *IntersectionDevice) Call() {
	id.L.Speak()
	id.S.Display()
}
func (id *IntersectionDevice) Back() {
	id.S.Back()
}

func (id *IntersectionDevice) ReConnect() {
	//重连屏
	if !id.S.IsLive {
		conn, err := net.DialTimeout("tcp", id.Info.ScreenIp+":5000", 5*time.Second)
		if err != nil {
			logrus.Error("连接", id.Info.ScreenIp, "失败!error:", err)
			return
		}
		logrus.Info("连接", id.Info.ScreenIp, "成功!")
		id.S.Conn = conn
		id.S.IsLive = true
	}
	//todo 重连loudspeaker
}

func (id *IntersectionDevice) Correct() {
	DoCorrectTime(id.S)
	DoCorrectTime(id.L)
}
