using Assets.Scripts.Devices.Ant;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using Assets.Scripts.Devices.Ant.Interfaces;

public class DeviceView : MonoBehaviour
{
    [SerializeField]
    private string mType;

    private SensorType SensorType
    {
        get
        {
            //Debug.Log(mType);
            Enum.TryParse(mType, out SensorType sensorType);
            return sensorType;
        }
    }

    private GameObject mSearchButton;
    private GameObject mPairButton;
    private GameObject mDisconnectButton;
    private GameObject unconnectionPanel;
    private GameObject connectionPanel;
    private Text searchState;
    private ConnectDeviceModal deviceModal;
    private Text title;
    private Text noDevice;
    private Text powerValue;
    private Text cadenceValue;
    private Text speedValue;
    private Text heartRateValue;
    private Image logo;
    /// <summary>
    /// 没有设备的logo
    /// </summary>
    private Sprite sprite0;
    /// <summary>
    /// 连接中的logo
    /// </summary>
    private Sprite sprite1;
    /// <summary>
    /// 已连接的logo
    /// </summary>
    private Sprite sprite3;

    private float timer = 1.0f;
    private void Awake()
    {
        title = this.transform.Find("Title").GetComponent<Text>();
        noDevice = this.transform.Find("NoDevice").GetComponent<Text>();
        unconnectionPanel = this.transform.Find("UnconnectionPanel").gameObject;
        mSearchButton = unconnectionPanel.transform.Find("SearchButton").gameObject;
        mPairButton = unconnectionPanel.transform.Find("PairButton").gameObject;
        searchState = unconnectionPanel.transform.Find("SearchState").GetComponent<Text>();
        mPairButton.SetActive(false);


        logo = this.transform.Find("Logo").GetComponent<Image>();
        InitLogo();

        connectionPanel = this.transform.Find("ConnectionPanel").gameObject;
        mDisconnectButton = connectionPanel.transform.Find("DisconnectBtn").gameObject;
        var powerValueObj = connectionPanel.transform.Find("PowerValue");
        if(powerValueObj != null)
        {
            powerValue = powerValueObj.gameObject.GetComponent<Text>();
        }
        var cadenceValueObj = connectionPanel.transform.Find("CadenceValue");
        if (cadenceValueObj != null) {
            cadenceValue = cadenceValueObj.gameObject.GetComponent<Text>();
        }
        var speedValueObj = connectionPanel.transform.Find("SpeedValue");
        if (speedValueObj != null)
        {
            speedValue = speedValueObj.gameObject.GetComponent<Text>();
        }

        var heartRateValueObj = connectionPanel.transform.Find("HeartRateValue");
        if(heartRateValueObj != null)
        {
            heartRateValue = heartRateValueObj.gameObject.GetComponent<Text>();
        }

        connectionPanel.SetActive(false);

        UIManager.AddEvent(mPairButton, EventTriggerType.PointerClick, new UnityAction<UnityEngine.EventSystems.BaseEventData>(e =>
        {
            if (deviceModal == null)
            {
                var obj = Resources.Load("UI/Prefab/Device/ConnectDeviceModal");
                GameObject gameObject = (GameObject)Instantiate(obj);
                deviceModal = gameObject.GetComponent<ConnectDeviceModal>();
            }
            deviceModal.SensorType = this.SensorType;
            UIManager.Show(deviceModal, null, true);
        }));

        UIManager.AddEvent(mDisconnectButton, EventTriggerType.PointerClick, new UnityEngine.Events.UnityAction<BaseEventData>(e => {
            //var device = GetDevice();
            //if(device != null && device.State == DeviceState.Connected)
            //{
            //    device.Disconnect();
            //}

            var obj = Resources.Load("UI/Prefab/Device/ConnectDeviceModal");
            GameObject gameObject = (GameObject)Instantiate(obj);
            deviceModal = gameObject.GetComponent<ConnectDeviceModal>();
            deviceModal.SensorType = this.SensorType;
            UIManager.Show(deviceModal, null, true);
        }));

    }

    void InitLogo()
    {
        if (SensorType == SensorType.Power)
        {
            sprite0 = Resources.Load<Sprite>("Images/Devices/Power_0");
            sprite1 = Resources.Load<Sprite>("Images/Devices/Power_1");
            sprite3 = Resources.Load<Sprite>("Images/Devices/Power_3");
        }
        else if (SensorType == SensorType.SpeedCadence)
        {
            sprite0 = Resources.Load<Sprite>("Images/Devices/Speed_0");
            sprite1 = Resources.Load<Sprite>("Images/Devices/Speed_1");
            sprite3 = Resources.Load<Sprite>("Images/Devices/Speed_3");
        }
        else if (SensorType == SensorType.Cadence)
        {
            sprite0 = Resources.Load<Sprite>("Images/Devices/Cadence_0");
            sprite1 = Resources.Load<Sprite>("Images/Devices/Cadence_1");
            sprite3 = Resources.Load<Sprite>("Images/Devices/Cadence_3");
        }
        else if (SensorType == SensorType.HeartRate)
        {
            sprite0 = Resources.Load<Sprite>("Images/Devices/Heart Rate_0");
            sprite1 = Resources.Load<Sprite>("Images/Devices/Heart Rate_1");
            sprite3 = Resources.Load<Sprite>("Images/Devices/Heart Rate_3");
        }
        else
        {
            sprite0 = Resources.Load<Sprite>("Images/Devices/Trainer_0");
            sprite1 = Resources.Load<Sprite>("Images/Devices/Trainer_1");
            sprite3 = Resources.Load<Sprite>("Images/Devices/Trainer_3");
        }
    }

    // Start is called before the first frame update
    void Start()
    {
        Main();
    }

    // Update is called once per frame
    void Update()
    {
        timer -= Time.deltaTime;
        if (timer <= 0)
        {
            Main();

            timer = 1.0f;
        }
    }

    void Main()
    {
        var connectedDevice = GetCurrentDevice();
        if(connectedDevice == null)
        {
            connectedDevice = GetDevice();
        }
        if(connectedDevice == null)
        {
            unconnectionPanel.SetActive(true);
            connectionPanel.SetActive(false);

            logo.sprite = sprite0;
            noDevice.text = "NO DEVICE";
            searchState.text = "Searching...";

            switch (SensorType)
            {
                case SensorType.None:
                    break;
                case SensorType.Cadence:
                    title.text = "Cadence Sensor";
                    break;
                case SensorType.HeartRate:
                    title.text = "Heart Rate Monitor";
                    break;
                case SensorType.Power:
                    title.text = "Power Meter";
                    break;
                case SensorType.Speed:
                    break;
                case SensorType.SpeedCadence:
                    title.text = "Speed Meter";
                    break;
                case SensorType.Trainer:
                    title.text = "Smart Trainer";
                    
                    break;
                case SensorType.VirtualPower:
                    break;
                default:
                    break;
            }
            var hasDevice = AntConnector.Instance().discoveredDevices.Any(d => d.Sensor == SensorType);
            if (hasDevice)
            {
                mSearchButton.SetActive(false);
                mPairButton.SetActive(true);
                logo.sprite = sprite1;
            }
            else
            {
                mSearchButton.SetActive(true);
                mPairButton.SetActive(false);
            }
        }
        else if(connectedDevice.State == DeviceState.Connecting)
        {
            unconnectionPanel.SetActive(true);
            connectionPanel.SetActive(false);
            logo.sprite = sprite1;

            title.text = connectedDevice.Name;
            noDevice.text = connectedDevice.DeviceNumber.ToString();
            searchState.text = "Connecting...";
        }
        else if (connectedDevice.State == DeviceState.Connected)
        {
            unconnectionPanel.SetActive(false);
            connectionPanel.SetActive(true);
            logo.sprite = sprite3;

            title.text = connectedDevice.Name;
            noDevice.text = connectedDevice.DeviceNumber.ToString();
            noDevice.color = Color.white;
            switch (SensorType)
            {
                case SensorType.None:
                    break;
                case SensorType.Cadence:
                    cadenceValue.text = (connectedDevice as ICadenceDevice).Cadence.ToString();
                    break;
                case SensorType.HeartRate:
                    heartRateValue.text = (connectedDevice as IHeartRateDevice).HeartRate.ToString();
                    break;
                case SensorType.Power:
                    powerValue.text = (connectedDevice as IPowerDevice).Power.ToString();
                    break;
                case SensorType.Speed:
                    break;
                case SensorType.SpeedCadence:
                    speedValue.text = (connectedDevice as ISpeedDevice).Speed.ToString();
                    break;
                case SensorType.Trainer:                    
                    powerValue.text = (connectedDevice as IPowerDevice).Power.ToString();
                    //cadenceValue.GetComponent<Text>().text = (connectedDevice as ICadenceDevice).Cadence.ToString();
                    //speedValue.GetComponent<Text>().text = (connectedDevice as ISpeedDevice).Speed.ToString();
                    break;
                case SensorType.VirtualPower:
                    break;
                default:
                    break;
            }
        }
        
    }

    AbstractAntDevice GetCurrentDevice()
    {
        return AntConnector.Instance().discoveredDevices.FirstOrDefault(d => (d.State == DeviceState.Connected || d.State == DeviceState.Connecting) && d.Sensor == SensorType);
    }

    /// <summary>
    /// 获取已经连接的设备
    /// </summary>
    /// <returns></returns>
    AbstractAntDevice GetDevice()
    {
        //return AntConnector.Instance().discoveredDevices.FirstOrDefault(d => (d.State == DeviceState.Connected || d.State == DeviceState.Connecting) && d.Sensor == SensorType);
        var devices = AntConnector.Instance().discoveredDevices.Where(d => (d.State == DeviceState.Connected));
        switch (SensorType)
        {
            case SensorType.None:
                break;
            case SensorType.Cadence:
                return devices.FirstOrDefault(d => d is ICadenceDevice);                
            case SensorType.HeartRate:
                return devices.FirstOrDefault(d => d is IHeartRateDevice);
            case SensorType.Power:
                var item = devices.FirstOrDefault(d => d is IPowerDevice);
                //if (powerValue != null)
                //{
                //    powerValue.GetComponent<Text>().text = (item as IPowerDevice).Power.ToString();
                //}
                return item;
            case SensorType.Speed:
            case SensorType.SpeedCadence:
                return devices.FirstOrDefault(d => d is ISpeedDevice);
            case SensorType.Trainer:
                var item3 = devices.FirstOrDefault(d => d.Sensor == SensorType.Trainer);
                return item3;                
            case SensorType.VirtualPower:
                break;
            default:
                return null;
        }
        return null;
    }
}
