package lc

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

type SmartXServer interface {
	Serve()
}

func StartSmartXServer(s SmartXServer) {
	s.Serve()
}

type IntersectionServer struct {
	MainState   byte
	SubState    byte
	MainDevices []IDevice
	SubDevices  []IDevice
	ReTicker    *time.Ticker
	Main        *time.Ticker
	Sub         *time.Ticker
}

type MainNotifier struct{ s *IntersectionServer }

// Notify 主路来车,通知支路设备
func (m MainNotifier) Notify() {
	m.s.Main.Reset(5 * time.Second)
	if m.s.MainState != 1 {
		m.s.MainState = 1
		for _, v := range m.s.SubDevices {
			gopool.Go(v.Call)
		}
	}
}

type SubNotifier struct{ s *IntersectionServer }

// Notify 支路来车,通知主路设备
func (s SubNotifier) Notify() {
	s.s.Sub.Reset(5 * time.Second)
	if s.s.SubState != 1 {
		s.s.SubState = 1
		for _, v := range s.s.MainDevices {

			gopool.Go(v.Call)

		}
	}
}

func (is *IntersectionServer) Serve() {
	RegisterCallback(1, &SubNotifier{is})
	RegisterCallback(0, &MainNotifier{is})
	//先创建响应设备
	for _, v := range util.Config.OutputDevices {
		iDevice := &IntersectionDevice{
			Info: v,
		}
		iDevice.ReConnect() //初次连接
		if iDevice.Info.Branch == 1 {
			is.MainDevices = append(is.MainDevices, iDevice)
		} else {
			is.SubDevices = append(is.SubDevices, iDevice)
		}
	}
	logrus.Info("主路输出设备列表:", is.MainDevices)
	logrus.Info("支路输出设备列表:", is.SubDevices)
	for {
		select {
		case <-is.Main.C: //检查主路状态->支路输出设备回到初始状态
			for _, v := range is.SubDevices {
				if is.MainState == 1 {
					gopool.Go(v.Back)
				}
			}
			is.MainState = 0
		case <-is.Sub.C: //检查支路状态->主路输出设备作出响应
			for _, v := range is.MainDevices {
				if is.SubState == 1 {
					gopool.Go(v.Back)
				}
			}
			is.SubState = 0
		case <-is.ReTicker.C: //每19s检查并尝试重连
			gopool.Go(func() {
				for _, v := range is.MainDevices {
					v.ReConnect()
				}
			})
			gopool.Go(func() {
				for _, v := range is.SubDevices {
					v.ReConnect()
				}
			})
		}
	}
}

// LServer ###
// ===
// ===
// ===
// === todo 服务器模式没测通,屏没有连接服务器
