using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using System.Xml;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net;
using System.IO;
using tpDomeWinAPP.Models;

namespace tpDomeWinAPP.Service
{
    public class webRequestSvc
    {
         
        //public async Task<List<device_value>> GetIotData(string urlString, List<device_value> deviceList, string deviceID)
        //{
        //    //string[] ss = urlString.Split('/');
        //    //string deviceID = ss[ss.Length - 2];
        //    string result = string.Empty;

        //    HttpClient client = new HttpClient();

        //    var byteArray = Encoding.ASCII.GetBytes("stanGG:St12345678");
        //    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
        //    try
        //    {
        //        HttpResponseMessage response = await client.GetAsync(urlString);
        //        HttpContent content = response.Content;
        //        // ... Check Status Code                                
        //        Console.WriteLine("Response StatusCode: " + (int)response.StatusCode);
        //        // ... Read the string.
        //        result = await content.ReadAsStringAsync();
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }

        //    XmlDocument doc = new XmlDocument();
        //    doc.LoadXml(result);
        //    XmlElement xmlRoot = doc.DocumentElement;
        //    //string jsonText = JsonConvert.SerializeXmlNode(doc);
        //    //JObject resultVal = (JObject)JsonConvert.DeserializeObject(jsonText);
        //    if (xmlRoot.ChildNodes.Count > 0)
        //    {
        //        foreach (XmlNode OneNode in xmlRoot.ChildNodes)
        //        {
        //            String StrNodeName = OneNode.Name.ToString();
        //            if (StrNodeName == "ref")
        //            {
        //                string v0 = OneNode.Attributes[0].Value;
        //                // if (v0 == "RH") MessageBox.Show("RH");

        //                //            維修       開機狀態    報警      保養
        //                //if (new[] { "Maintain", "Status", "Alarm", "Maintenance", "Temp", "RH", "AlarmState" }.Contains(v0))
        //                if (new[] { "name", "val", "href" }.Contains(v0))
        //                {
        //                    switch (v0)
        //                    {
        //                        //case "Maintain": v0 = v0 + " 維修 "; break;
        //                        //case "Status": v0 = v0 + " 開1 關0 "; break;
        //                        //case "Alarm": v0 = v0 + " 報警1 無0 "; break;
        //                        //case "Maintenance": v0 = v0 + " 保養1 無0 "; break;
        //                        //case "Temp": v0 = v0 + " 溫度 "; break;
        //                        //case "RH": v0 = v0 + " 濕 "; break;
        //                        //case "AlarmState": v0 = v0 + " 電力異常 "; break;
        //                        case "name": v0 = v0 + " 維修 "; break;
        //                        case "val": v0 = v0 + " 開1 關0 "; break; 
        //                        case "href": v0 = v0 + " 保養1 無0 "; break; 
        //                    }
        //                    device_value device = new device_value();
        //                    device_value.id = deviceID;
        //                    device.Name = v0;
        //                    if (OneNode.Attributes[3].Name == "display")
        //                    {
        //                        device.display = OneNode.Attributes[3].Value;
        //                        device.result_value = device.display.Split(' ')[0];
        //                    }
        //                    deviceList.Add(device);
        //                }
        //            }
        //            else if (StrNodeName == "bool")
        //            {
        //                string v0 = OneNode.Attributes[0].Value;
        //                //            維修       開機狀態    報警      保養
        //                if (new[] { "Maintain", "Status", "Alarm", "Maintenance", "out" }.Contains(v0))
        //                {
        //                    device_value device = new device_value();
        //                    device.id = deviceID;
        //                    device.Name = v0;
        //                    if (OneNode.Attributes[4].Name == "display")
        //                    {
        //                        device.display = OneNode.Attributes[4].Value;
        //                        device.result_value = device.display.Split(' ')[0];
        //                    }
        //                    deviceList.Add(device);
        //                }
        //            }
        //            else if (StrNodeName == "obj")
        //            {
        //                string v0 = OneNode.Attributes[0].Value;
        //                //           維修       開機狀態    報警      保養
        //                if (new[] { "Maintain", "Status", "Alarm", "Maintenance", "out" }.Contains(v0))
        //                {
        //                    device_value device = new device_value();
        //                    device.id = deviceID;
        //                    device.Name = v0;
        //                    if (OneNode.Attributes[4].Name == "display")
        //                    {
        //                        device.display = OneNode.Attributes[4].Value;
        //                        device.result_value = device.display.Split(' ')[0];
        //                    }
        //                    deviceList.Add(device);
        //                }
        //            }
        //        }
        //    }
        //    else
        //    {
        //        if (xmlRoot.Name == "bool")
        //        {
        //            // xmlRoot.Attributes[0].Value
        //            var item = xmlRoot.Attributes.GetNamedItem("display");
        //            var times = xmlRoot.Attributes.GetNamedItem("href").Value.ToString().Split('/');
        //            device_value device = new device_value();
        //            device.id = deviceID;
        //            device.Name = times[times.Length - 3];
        //            device.display = item.Value;
        //            device.result_value = device.display.Split(' ')[0];
        //            deviceList.Add(device);
        //        }
        //        string data = xmlRoot.Name;

        //    }
        //    return deviceList;
        //}

        public List<device_value2> obixQuery(string urlString, string bql)
        {
            List<device_value2> result = new List<device_value2>();
            //String username = "obixUser";
            //String password = "Admin123456";
            String username = "stanGG";
            String password = "St12345678";
            String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
            String API_Url = urlString;

            HttpWebRequest Postrequest = (HttpWebRequest)WebRequest.Create(API_Url);
            Postrequest.Method = "POST";
            Postrequest.Headers.Add("Authorization", "Basic " + encoded);
            Postrequest.PreAuthenticate = true;

            using (var streamWriter = new StreamWriter(Postrequest.GetRequestStream()))
            {
                string json = "<str val='" + bql + "'/>";

                streamWriter.Write(json);
            }

            HttpWebResponse response = (HttpWebResponse)Postrequest.GetResponse();
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(responseString);
            //xmlDoc.Load("N4v1021.xml");//N4v1021

            //xmlDoc.Save("N4.xml"); 


            string jsonText = JsonConvert.SerializeXmlNode(xmlDoc);
           // JObject resultVal = (JObject)JsonConvert.DeserializeObject(jsonText);
            var data = Welcome.FromJson(jsonText);
            
            foreach (var item in data.Obj.Str)
            {
                device_value2 row = new device_value2();
                row.value = item.Val;
                string[] s1 = item.Val.Split(',');
                string[] s2 = s1[0].Split('/');
                row.tag_name = "";

                for (int i = 0; i < s2.Length; i++)
                {
                    if (i == s2.Length - 2)
                    {
                        row.point_name = s2[i];
                    }
                    else if (i == 1)
                    {
                        row.tag_name += s2[i];
                    }
                    else if (i > 1 && i < s2.Length - 2)
                    {
                        row.tag_name += "_" + s2[i].Replace("$3", "");
                    }
                }

                /*foreach (var ss in s2)
                {
                    if (ss.Contains('_'))
                    {
                        string[] s3 = ss.Split('_');
                        if (s3.Count() > 3)
                        {
                            row.tag_name = ss;
                            row.point_name = s2[s2.Length-2];
                            break;
                        }
                    }                   
                    //if (ss.Contains("_"))
                    //{
                    //    string sno1 = ss.Substring(0, 1); //第一碼為棟別
                    //    if (new[] { "H", "O", "C", "D", "M" }.Contains(sno1)) {
                    //        row.tag_name = ss; break;
                    //    }
                    //    //if (ss.Contains("H") || ss.Contains("O") || ss.Contains("C") || ss.Contains("D") || ss.Contains("M"))
                    //    //{
                    //    //    
                    //    //}
                    //}
                }
                */
                result.Add(row);
                //row.tag_name = s2.Where( x => x.Contains("_") && 
                //    (x.Contains("H") || x.Contains("O") || x.Contains("C") || x.Contains("D") || x.Contains("M")))
                //    .FirstOrDefault();

            } 
            return result;
        }
    }
}