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.AVL09.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)
        {
            int L = temp.data_body.Length;
            int S = 0;
            byte[] bt1 = new byte[5];//图片序号（00001～99999）
            byte[] bt2 = new byte[3];//包总数（001～999）
            byte[] bt3 = new byte[3];//包序数（001～999）
            byte[] bt4, bt5, bt6;
            Array.Copy(temp.data_body, 17, bt1, 0, bt1.Length);
            Array.Copy(temp.data_body, 22, bt2, 0, bt2.Length);
            Array.Copy(temp.data_body, 25, bt3, 0, bt3.Length);

            string imgNum = System.Text.Encoding.ASCII.GetString(bt1);
            string pTotal = System.Text.Encoding.ASCII.GetString(bt2);
            string pNum = System.Text.Encoding.ASCII.GetString(bt3);
            string imgtime, imglatlng;

            if (pNum == "001")
            {
                //59
                bt4 = new byte[12];//拍照时间
                bt6 = new byte[19];//定位信息
                bt5 = new byte[L - 62];//图片数据
                S = 59;
                Array.Copy(temp.data_body, 28, bt4, 0, bt4.Length);
                Array.Copy(temp.data_body, 40, bt6, 0, bt6.Length);
                Array.Copy(temp.data_body, S, bt5, 0, bt5.Length);
                imgtime = System.Text.Encoding.ASCII.GetString(bt4).Trim();
                imglatlng = System.Text.Encoding.ASCII.GetString(bt6).Trim();

            }
            else
            {
                //28
                bt5 = new byte[L - 31];//图片数据
                S = 28;
                Array.Copy(temp.data_body, S, bt5, 0, bt5.Length);
                imgtime = "";
                imglatlng = "";
            }


            string path = "";
            path = string.Format("{0}\\{1}\\{2}\\", System.Configuration.ConfigurationManager.AppSettings["img"], temp.imei, DateTime.Now.ToString("yyyyMM"));
            try
            {
                Directory.CreateDirectory(path);
            }
            catch
            {
                path = string.Format("{3}\\{0}\\{1}\\{2}\\", "IMG", temp.imei, DateTime.Now.ToString("yyyyMM"), Directory.GetCurrentDirectory());
                Directory.CreateDirectory(path);
            }
            string xmlPath = string.Format("{0}\\{1}_{2}_{3}.xml", path, DateTime.Now.ToString("yyyyMMdd"), imgNum, pTotal.ToString());
            if (!File.Exists(xmlPath))
            {
                HandleBeforePicture(path);
            }
            string data = BitConverter.ToString(bt5, 0, bt5.Length).Replace("-", "");
            GenerateTempData(xmlPath, temp.imei, pNum, pTotal, imgtime, imglatlng, data);
            if (pNum == pTotal)
            {
                GeneratePicture(xmlPath);
            }

        }

        /// <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, string imei, string pNum, string pTotal, string imgtime, string imglatlng, string data)
        {
            XDocument xDoc = null;
            XElement xRoot = null;
            XElement xElement = null;
            try
            {
                if (!File.Exists(path))
                {
                    xRoot = new XElement("Root", new XAttribute("Total", pTotal),
                        new XAttribute("Time", imgtime),
                        new XAttribute("LatLng", imglatlng),
                        new XAttribute("IMEI", imei)
                        );
                    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);
                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);
                string _imgTime = xRoot.Attribute("Time").Value;
                string _imglatlng = xRoot.Attribute("LatLng").Value;
                string _imgimei = xRoot.Attribute("IMEI").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}_{1}_{2}.jpg", _imgTime, _imgimei, _imglatlng));
                    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);
            }
        }

    }
}
