using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TZONE.Model;
using System.IO;
using System.Xml.Linq;
using log4net;
using System.Reflection;
using System.Drawing;
using System.Drawing.Imaging;

namespace TZONE.AVL08.DU
{
    public class AnalyzeHandle
    {
        ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        /// <summary>
        /// Data Analysis
        /// </summary>
        /// <param name="temp"></param>
        public void AnalyzeData(tempdata temp)
        {
            string msg = Encoding.Default.GetString(temp.data_body, 0, temp.data_body.Length).Trim('\0');
            HandlePicture(msg);
        }

        private void HandlePicture(string msg)
        {
            string imei = "";
            string imgNum = "";
            int pTotal = 0;
            int pNum = 0;
            string data = "";
            try
            {
                imei = msg.Substring(2, 15);
                imgNum = msg.Substring(17, 5);
                pTotal = Convert.ToInt32(msg.Substring(22, 3));
                pNum = Convert.ToInt32(msg.Substring(25, 3));
                data = msg.Substring(28, msg.IndexOf("#") - 28);
                string path = "";
                path = string.Format("{0}\\{1}\\{2}\\", System.Configuration.ConfigurationManager.AppSettings["img"], imei, DateTime.Now.ToString("yyyyMM"));
                try
                {
                    Directory.CreateDirectory(path);
                }
                catch
                {
                    path = string.Format("{3}\\{0}\\{1}\\{2}\\", "IMG", imei, DateTime.Now.ToString("yyyyMM"), Directory.GetCurrentDirectory());
                    Directory.CreateDirectory(path);
                }
                //if (pNum == 1)
                //{
                //    HandleBeforePicture(path);
                //}
                string xmlPath = string.Format("{0}\\{1}_{2}_{3}.xml", path, DateTime.Now.ToString("yyyyMMdd"), imgNum, pTotal.ToString());
                //If you find a new data packet before processing
                if (!File.Exists(xmlPath))
                {
                    HandleBeforePicture(path);
                }
                GenerateTempData(xmlPath, pNum, pTotal, data);
                //If the final package, the analytic picture
                if (pNum == pTotal)
                {
                    GeneratePicture(xmlPath);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }
        /// <summary>
        /// Generate temporary files
        /// </summary>
        /// <param name="path"></param>
        /// <param name="pNum"></param>
        /// <param name="pTotal"></param>
        /// <param name="data"></param>
        private void GenerateTempData(string path, int pNum, int pTotal, string data)
        {
            XDocument xDoc = null;
            XElement xRoot = null;
            XElement xElement = null;
            try
            {
                if (!File.Exists(path))
                {
                    xRoot = new XElement("Root", new XAttribute("Total", pTotal));
                    xDoc = new XDocument(new XDeclaration("1.0", "utf-8", "no"), xRoot);
                }
                else
                {
                    xDoc = XDocument.Load(path);
                    xRoot = xDoc.Root;
                }
                var tmpList = xRoot.Descendants("Item").Where(a => a.Attribute("ID").Value == pNum.ToString());
                if (tmpList.Count() > 0)
                {
                    foreach (XElement xe in tmpList)
                        xe.Remove();
                }
                xElement = new XElement("Item", new XAttribute("ID", pNum), data);
                xRoot.Add(xElement);
                xRoot.Save(path);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }
        /// <summary>
        /// Students to become full picture
        /// </summary>
        /// <param name="path"></param>
        private void HandleBeforePicture(string path)
        {
            try
            {
                DirectoryInfo dirInfo = new DirectoryInfo(path);
                var files = dirInfo.GetFiles("*.xml");
                foreach (var file in files)
                {
                    GeneratePicture(file.FullName);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }
        /// <summary>
        /// Generated picture
        /// </summary>
        /// <param name="path"></param>
        private void GeneratePicture(string path)
        {
            try
            {
                XDocument xDoc = XDocument.Load(path);
                XElement xRoot = xDoc.Root;
                int count = Convert.ToInt32(xRoot.Attribute("Total").Value);
                var list = xRoot.Elements().OrderBy(a => a.Attribute("ID").Value).ToDictionary(a => Convert.ToInt32(a.Attribute("ID").Value), a => a.Value);
                if (list.Keys.Any(a => a > 6))
                {
                    StringBuilder sb = new StringBuilder();
                    string tmp = null;
                    for (int i = 1; i <= count; i++)
                    {
                        if (list.ContainsKey(i))
                        {
                            sb.Append(list[i]);
                            tmp = list[i];
                        }
                        else
                        {
                            sb.Append(i <= 6 ?  TZONE.GPSSocketServer.Common.Utils.PicTitle[i - 1] : (tmp ?? ""));
                        }
                    }
                    string msg = sb.ToString();
                    if (msg.LastIndexOf("FFD9") + 4 != msg.Length)
                        msg += msg + "FFD9";
                    byte[] byteData = TZONE.GPSSocketServer.Common.Utils.HexToByte(sb.ToString());
                    MemoryStream ms = new MemoryStream(byteData);
                    ms.Position = 0;
                    Image image = Image.FromStream(ms);
                    string tmpPath = path.Replace(".xml", string.Format("_{0}.jpg", DateTime.Now.ToString("hhmmss")));
                    try
                    {
                        image.Save(tmpPath, ImageFormat.Jpeg);
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex.Message);
                    }
                    image.Dispose();
                    ms.Close();
                }
                File.Delete(path);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }
    }
}
