using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TZONE.Model;
using log4net;
using System.Reflection;

namespace TZONE.AVL09.DT
{
    public class AnalyzeHandle
    {
        ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        /// <summary>
        /// Data Analysis
        /// </summary>
        /// <param name="temp"></param>
        public void AnalyzeData(tempdata temp)
        {
            try
            {
                schoolbus_normal model = new schoolbus_normal();
                model.ServerTime = Convert.ToDateTime(temp.server_time);
                model.IMEI = temp.imei;
                model.PID = temp.PID;
                model.TypeID = temp.type_id;
                model.Lat = 0;
                model.Lng = 0;
                model.data_body = temp.data_body;
                if (ProtocolAnalyze(ref model))
                {
                    DataAccess.data_Facade dal = new DataAccess.data_Facade();
                    //dal.insert_SchoolBus_Realtime(model);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
            

            try
            {
                tagdata tagdatamodel = new tagdata();
                tagdatamodel.servertime = Convert.ToDateTime(temp.server_time);
                tagdatamodel.imei = temp.imei;
                tagdatamodel.data_body = temp.data_body;
                if (TagProtocolAnalyze(ref tagdatamodel))
                {
                    DataAccess.data_Facade dal = new DataAccess.data_Facade();
                    //dal.update_tag_data(tagdatamodel);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }

        }

        /// <summary>
        /// Protocol analysis
        /// </summary>
        /// <param name="model"></param>
        private bool ProtocolAnalyze(ref schoolbus_normal model) 
        {
            try
            {
                /*
                 * Format：
                 * $T(2Bytes)+Len(2Bytes)+IMEI(15Bytes+|+RTC(14Bytes)+|+LOCATION(19Bytes)+|+TagCount(1Byte)+|TAGID（4Bytes)....|+Checksum(4Bytes)+ \r\n(2Bytes) 
                 */
                string len = BitConverter.ToString(model.data_body, 2, 2).Replace("-", "");
                int L_len = Convert.ToInt32(len, 16);
                //IMEI
                model.IMEI = Encoding.Default.GetString(model.data_body, 4, 15).Trim('\0');
                model.RTC = DateTime.ParseExact(Encoding.Default.GetString(model.data_body, 20, 14).Trim('\0'), "yyyyMMddHHmmss", null);
                model.Lat = GPSSocketServer.Common.Utils.GetDTLat(Encoding.Default.GetString(model.data_body, 35, 19).Trim('\0').Substring(0, 9));
                model.Lng = GPSSocketServer.Common.Utils.GetDTLng(Encoding.Default.GetString(model.data_body, 35, 19).Trim('\0').Substring(9));
                string tagcount = BitConverter.ToString(model.data_body, 55, 1).Replace("-", "");
                int L_tagcount = Convert.ToInt32(tagcount, 16);
                string tagid = "";
                for (int i = 0; i < L_tagcount; i++)
                {
                    tagid += BitConverter.ToString(model.data_body, 57 + (i * 4), 4).Replace("-", "")+",";
                }
                model.Tag = tagid.Trim(',');
                return true;
            }
            catch (Exception)
            {
                return false;
            }
             
        }

        /// <summary>
        /// Protocol analysis
        /// </summary>
        /// <param name="model"></param>
        private bool TagProtocolAnalyze(ref tagdata model)
        {
            try
            {
                /*
                 * Format：
                 * $T(2Bytes)+Len(2Bytes)+IMEI(15Bytes+|+RTC(14Bytes)+|+LOCATION(19Bytes)+|+TagCount(1Byte)+|TAGID（4Bytes)....|+Checksum(4Bytes)+ \r\n(2Bytes) 
                 */
                model.RTC = DateTime.ParseExact(Encoding.Default.GetString(model.data_body, 20, 14).Trim('\0'), "yyyyMMddHHmmss", null);
                model.lat = GPSSocketServer.Common.Utils.GetDTLat(Encoding.Default.GetString(model.data_body, 35, 19).Trim('\0').Substring(0, 9));
                model.lng = GPSSocketServer.Common.Utils.GetDTLng(Encoding.Default.GetString(model.data_body, 35, 19).Trim('\0').Substring(9));
                string tagcount = BitConverter.ToString(model.data_body, 55, 1).Replace("-", "");
                int L_tagcount = Convert.ToInt32(tagcount, 16);
                string tagid = "";
                for (int i = 0; i < L_tagcount; i++)
                {
                    tagid += BitConverter.ToString(model.data_body, 57 + (i * 4), 4).Replace("-", "") + ",";
                }
                model.tagid = tagid.Trim(',');
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
