using LovenseBLE;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace LovenseBlueToothLEDemo
{
    public partial class Form1 : Form
    {

        private List<LovenseToy> toys = new List<LovenseToy>();
        private bool enable_BLE;


        public Form1()
        {

            InitializeComponent();

            GetSupportedCommand();
            LovenseBLETools.GetInstance().InitCallback();
            LovenseBLETools.GetInstance().CheckBLEStatus();

            LovenseBLETools.GetInstance().lovenseNotifyEvent += Form1_LovenseNotifyMessage;
            LovenseBLETools.GetInstance().addToyEvent += Form1_addToyEvent;
            LovenseBLETools.GetInstance().connectChangeEvent += Form1_connectChangeEvent;
            LovenseBLETools.GetInstance().eventsAPIevent += Form1_eventsAPIevent;
            LovenseBLETools.GetInstance().batteryEvent += Form1_eventsBattery;
        }

        private void Form1_eventsBattery(string id, string battery)
        {
            this.Invoke((MethodInvoker)delegate
            {
                int index = toys.FindIndex(t => t.id == id);
                if (index != -1)
                {
                    if (index < listView.Items.Count)
                    {
                        listView.Items[index].SubItems[5].Text = "" + battery;
                    }
                }
                AddText("get Battery:" + id + "," + battery);
            });
        }

        private void Form1_eventsAPIevent(string id, LovenseDataReportingEventType type, int hardwareType, int value)
        {
            this.Invoke((MethodInvoker)delegate
            {
                AddText("get events->" + id + ",event type:" + type + ",hardwareType:" + hardwareType + ",value:" + value);
            });
        }


        private void Form1_connectChangeEvent(string id, bool connected)
        {
            if(connected)
            {
                LovenseBLETools.GetInstance().SendCommand(id, new LovenseCommand() { commandType = LovenseCommandType.GET_BATTERY });
            }
            this.Invoke((MethodInvoker)delegate
            {
                int index = toys.FindIndex(t => t.id == id);
                if (index != -1)
                {
                    if (index < listView.Items.Count)
                    {
                        listView.Items[index].SubItems[4].Text = "" + connected;
                    }
                }
                AddText("ConnectChanged:" + id + "," + connected);
            });
        }

        public async void GetSupportedCommand()
        {
            string supportText = @",symbol,type,showName,func
0,1.5,version,,
1,[  ""l""],Ambi,Ambi,""{ """"p"""": false,  """"r"""": false,  """"v2"""": false,  """"v1"""": false,  """"v"""": true}
            ""
2,[  ""ca""],Mission2,Mission2,""{  """"p"""": false,  """"r"""": false,  """"v2"""": false,  """"v1"""": false,  """"v"""": true}""
3,[  ""su""],c20,C20,""{  """"p"""": false,  """"r"""": false,  """"v2"""": false,  """"v1"""": false,  """"v"""": true}""
4,[  ""t""],Calor,Calor,""{  """"p"""": false,  """"r"""": false,  """"v2"""": false,  """"v1"""": false,  """"v"""": true}""
5,[  ""r""],Diamo,Diamo,""{  """"p"""": false,  """"r"""": false,  """"v2"""": false,  """"v1"""": false,  """"v"""": true}""
6,[  ""j""],Dolce,Dolce,""{  """"p"""": false,  """"r"""": false,  """"v2"""": true,  """"v1"""": true,  """"v"""": true}""
7,[  ""w""],Domi,Domi,""{  """"p"""": false,  """"r"""": false,  """"v2"""": false,  """"v1"""": false,  """"v"""": true}""
8,[  ""p""],Edge,Edge,""{  """"p"""": false,  """"r"""": false,  """"v2"""": true,  """"v1"""": true,  """"v"""": true}""
9,[  ""ef""],Exomoon,Exomoon,""{  """"p"""": false,  """"r"""": false,  """"v2"""": false,  """"v1"""": false,  """"v"""": true}""
10,[  ""x""],Ferri,Ferri,""{  """"p"""": false,  """"r"""": false,  """"v2"""": false,  """"v1"""": false,  """"v"""": true}""
11,[  ""ei""],Flexer,Flexer,""{  """"p"""": false,  """"r"""": false,  """"v2"""": false,  """"v1"""": false,  """"v"""": true,  """"f"""": true}""
12,[  ""n""],Gemini,Gemini,""{  """"p"""": false,  """"r"""": false,  """"v2"""": true,  """"v1"""": true,  """"v"""": true}""
13,[  ""ea""],Gravity,Gravity,""{  """"p"""": false,  """"r"""": false,  """"v2"""": false,  """"v1"""": false,  """"v"""": true,  """"t"""": true,  """"s"""": false}""
14,[  ""ed""],Gush,Gush,""{  """"p"""": false,  """"r"""": false,  """"v2"""": false,  """"v1"""": false,  """"v"""": true}""
15,[  ""ba""],SolacePro,SolacePro,""{  """"p"""": false,  """"r"""": false,  """"v2"""": false,  """"v1"""": false,  """"v"""": false,  """"t"""": true,  """"pos"""": true}""
16,[  ""z""],Hush,Hush,""{  """"p"""": false,  """"r"""": false,  """"v2"""": false,  """"v1"""": false,  """"v"""": true}""
17,[  ""eb""],Hyphy,Hyphy,""{  """"p"""": false,  """"r"""": false,  """"v2"""": false,  """"v1"""": false,  """"v"""": true}""
18,[  ""u""],Lapis,Lapis,""{  """"p"""": false,  """"r"""": false,  """"v2"""": true,  """"v1"""": true,  """"v3"""": true,  """"v"""": true}""
19,[  ""s""],Lush,Lush,""{  """"p"""": false,  """"r"""": false,  """"v2"""": false,  """"v1"""": false,  """"v"""": true}""
20,""[  """"toyb"""",  """"b""""]"",Max,Max,""{  """"p"""": true,  """"r"""": false,  """"v2"""": false,  """"v1"""": false,  """"v"""": true}""
21,[  ""fs""],MiniXMachine,MiniXMachine,""{  """"p"""": false,  """"r"""": false,  """"v2"""": false,  """"v1"""": false,  """"v"""": true,  """"t"""": true}""
22,[  ""v""],Mission,Mission,""{  """"p"""": false,  """"r"""": false,  """"v2"""": false,  """"v1"""": false,  """"v"""": true}""
23,""[  """"toyc"""",  """"toya"""",  """"c"""",  """"a""""]"",Nora,Nora,""{  """"p"""": false,  """"r"""": true,  """"v2"""": false,  """"v1"""": false,  """"v"""": true}""
24,[  ""o""],Osci,Osci,""{  """"p"""": false,  """"r"""": false,  """"v2"""": false,  """"v1"""": false,  """"v"""": true}""
25,[  ""qa""],QA01,QA01,""{  """"p"""": false,  """"r"""": false,  """"v2"""": true,  """"v1"""": true,  """"v"""": true}""
26,[  ""el""],Ridge,Ridge,""{  """"p"""": false,  """"r"""": true,  """"v2"""": false,  """"v1"""": false,  """"v"""": true}""
27,[  ""h""],Solace,Solace,""{  """"p"""": false,  """"r"""": false,  """"v2"""": false,  """"v1"""": false,  """"v"""": false,  """"t"""": true,  """"d"""": true}""
28,[  ""q""],Tenera,Tenera,""{  """"p"""": false,  """"r"""": false,  """"v2"""": false,  """"v1"""": false,  """"v"""": true,  """"s"""": true}""
29,[  ""sd""],Vulse,Vulse,""{  """"p"""": false,  """"r"""": false,  """"v2"""": false,  """"v1"""": false,  """"v"""": true}""
30,[  ""f""],XMachine,XMachine,""{  """"p"""": false,  """"r"""": false,  """"v2"""": false,  """"v1"""": false,  """"v"""": true,  """"t"""": true}""
31,[  ""ez""],Gush2,Gush2,""{  """"p"""": false,  """"r"""": false,  """"v2"""": false,  """"v1"""": false,  """"v"""": false, """"o"""":true}""";

            //string url = "https://developer.lovense.com/LovenseToySupportConfig.csv";
            //HttpClient client = new HttpClient();
            //string supportText = await client.GetStringAsync(new Uri(url));

            LovenseBLETools.GetInstance().InitSupport(supportText, (InitSupportCommandStatus status) => {
                if (status == InitSupportCommandStatus.SUCCESS)
                {

                }
            });
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }


        private void Form1_addToyEvent(LovenseToy toy)
        {
            AddToy(toy);
            
        }

        private void Form1_LovenseNotifyMessage(LovenseNotifyType type,string id)
        {
            AddText(type.ToString());
        }

        private void Form1_Load_1(object sender, EventArgs e)
        {

        }

        private void scanBtn_Click(object sender, EventArgs e)
        {
            LovenseBLETools.GetInstance().StartBLEScan();
        }

        private void scanStopBtn_Click(object sender, EventArgs e)
        {
            LovenseBLETools.GetInstance().StopBLEScan();
        }


        private void connectBtn_Click(object sender, EventArgs e)
        {
            for(int i=0;i< listView.CheckedItems.Count;i++)
            {
                LovenseBLETools.GetInstance().ConnectToy(listView.CheckedItems[i].SubItems[0].Text);
            }
            
        }

        private void commandBtn_Click(object sender, EventArgs e)
        {
            
            for (int i = 0; i < listView.CheckedItems.Count; i++)
            {
                string id = listView.CheckedItems[i].SubItems[0].Text;
                string type = listView.CheckedItems[i].SubItems[2].Text;
                if (type == "SolacePro")
                {
                    LovenseBLETools.GetInstance().SendCommand(id, new LovenseCommand() { commandType=LovenseCommandType.POSITION,value=50 });

                    //LovenseBLETools.GetInstance().SendCommandsToSolacePro(id, new LovenseSolaceProCommand() { speedLevel = 50, strokeLow = 20, strokeHigh = 85 });
                }
                else {

                    LovenseCommandType[] support = LovenseBLETools.GetInstance().GetSupportedCommandsByType(type);
                    List<LovenseCommand> commands = new List<LovenseCommand>();
                    foreach (LovenseCommandType commandType in support)
                    {
                        LovenseCommand addCommand = new LovenseCommand();
                        addCommand.commandType = commandType;
                        addCommand.value = 10;
                        commands.Add(addCommand);
                    }
                    LovenseBLETools.GetInstance().SendCommands(id, commands.ToArray());
                }
            }
        }

        private void stopBtn_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < listView.CheckedItems.Count; i++)
            {
                string id = listView.CheckedItems[i].SubItems[0].Text;
                string type = listView.CheckedItems[i].SubItems[2].Text;
                LovenseBLETools.GetInstance().Stop(id,type);
            }
           
        }

        private void disconnectBtn_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < listView.CheckedItems.Count; i++)
            {
                LovenseBLETools.GetInstance().DisConnectToy(listView.CheckedItems[i].SubItems[0].Text);
            }
        }

        private void ListView_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            
        }

        private void AddToy(LovenseToy toy)
        {
            this.Invoke((MethodInvoker)delegate
            {
                if (toys.Contains(toy))
                {
                    return;
                }
                toys.Add(toy);
                var item1 = new ListViewItem(toy.id);
                item1.SubItems.Add(toy.name);
                item1.SubItems.Add(toy.type);
                item1.SubItems.Add(toy.mac);
                item1.SubItems.Add("False");
                item1.SubItems.Add("0");
                listView.Items.Add(item1);
                listView.ItemChecked += ListView_ItemChecked;
            });

        }

        public void AddText(string str)
        {
            this.Invoke((MethodInvoker)delegate
            {
                textBox1.AppendText($"notify:{str}\r\n");
                textBox1.SelectionStart = textBox1.Text.Length;
                textBox1.ScrollToCaret();
            });
        }

        private void eventsapiBtn_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < listView.CheckedItems.Count; i++)
            {
                string id = listView.CheckedItems[i].SubItems[0].Text;
                string type = listView.CheckedItems[i].SubItems[2].Text;
                if (type == "SolacePro")
                {
                    LovenseBLETools.GetInstance().StartSolaceProEventsAPI(id,1);
                }
                else
                {
                    LovenseBLETools.GetInstance().StartEventsAPI(id);
                }
            }
            
        }

        private void stopeventsapiBtn_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < listView.CheckedItems.Count; i++)
            {
                string id = listView.CheckedItems[i].SubItems[0].Text;
                string type = listView.CheckedItems[i].SubItems[2].Text;
                if (type == "SolacePro")
                {
                    LovenseBLETools.GetInstance().CloseSolaceProEventsAPI(id);
                }
                else
                {
                    LovenseBLETools.GetInstance().CloseEventsAPI(id);
                }
            }
        }
    }
}
