using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RCUHost.Protocols;
using System.IO;
using Common;
using Domain;
using Dao;
using RestSharp;

namespace RCUHost.Implement
{
    public class TFTPReceiver : GenericReceiverBase, IT_FTPReceiver
    {

        private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(TFTPReceiver));

        public ITFTP_SetRepository TFTPLogRepository { get; set; }
        public IHostRepository HostRepository { get; set; }
        public override CommandType CommandType
        {
            get { return CommandType.TFTPLog; }

        }
        public override void Process(ReceiverContext context)
        {
            //logger.Error(string.Format("收到白天起始时间命令回复，编码：{0}，IP：{1}", context.SystemHeader.Value.HostNumber.ToString(), context.RemoteEndPoint.Address.ToString() + ":" + context.RemoteEndPoint.Port.ToString()));
            var data = context.Data;


            string msg = context.RemoteEndPoint.Address.ToString() + ":" + context.RemoteEndPoint.Port.ToString() + ":" + Tools.ByteToString(context.Data);
            string hostnum = context.SystemHeader.Value.HostNumber.ToString();
            logger.Error("收到主机信息数据：" + msg);
            logger.Error("收到主机信息数据：" + hostnum);
            Host host = HostRepository.GetByHostNumber(hostnum);//.RemoteEndPoint.Address.ToString());

            if (host != null)
            {
                string dataHex = Tools.ByteToString(context.Data);

                int offset = StructConverter.SizeOf(context.SystemHeader);
                int length = context.Data.Length - offset - 2;
                using (MemoryStream stream = new MemoryStream(context.Data, offset, length))
                {
                    using (BinaryReader reader = new BinaryReader(stream))
                    {
                        byte isEnable = reader.ReadByte();//是否启用
                        int report_port = BitConverter.ToUInt16(reader.ReadBytes(2), 0);//局域网端口
                        int report_lasttime = BitConverter.ToUInt16(reader.ReadBytes(2), 0);//上传多久
                        int domain_len = reader.ReadByte();
                        byte[] domain_fact = reader.ReadBytes(domain_len);
                        string domainstring = Encoding.UTF8.GetString(domain_fact);

                        int hostid = host.ID;
                        int hotelid = host.SysHotel.ID;

                        bool isenable = false;
                        //日志开启状态
                        //FF：全开 00：全关
                        if (isEnable == 0xFF)
                        {
                            isenable = true;
                        }
                        string ti = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");


                        TFTP_Set t = new TFTP_Set();


                        t.HotelCode = host.SysHotel.Code;
                        t.HotelID = host.SysHotel.ID;

                        t.HostID = hostid;
                        t.RoomNumber = host.RoomNumber;

                        t.IsTrigger = isenable;
                        t.LastTime = report_lasttime;
                        t.TargetPort = report_port;
                        t.TargetDomain = domainstring;
                        t.CreateTime = ti;

                        TFTP_Set ttt = TFTPLogRepository.GetDataBy(hotelid, hostid);
                        if (ttt != null)
                        {

                            ttt.IsTrigger = isenable;
                            ttt.LastTime = report_lasttime;
                            ttt.TargetPort = report_port;
                            ttt.TargetDomain = domainstring;
                            ttt.CreateTime = ti;

                            TFTPLogRepository.Update(ttt);

                        }
                        else
                        {
                            TFTPLogRepository.Save(t);
                        }

                        string debug_log_report_url = RCUHost.TimingHelper.Common.debug_log_report_url;
                        string debug_log_report_mqtt_topic = "blw/tftp/report/"+hotelid;

                        string str = Newtonsoft.Json.JsonConvert.SerializeObject(t);
                        var client1 = new RestClient(debug_log_report_url);
                        var request1 = new RestRequest("/", Method.POST);

                        //注意方法是POST
                        //两个参数名字必须是 topic 和payload ，区分大小写的
                        request1.AddParameter("topic", debug_log_report_mqtt_topic);
                        request1.AddParameter("payload", str);


                        client1.ExecuteAsync(request1, (response) => { });
                    }
                }
            }

        }

        public byte[] CreateDataPacket()
        {
            SystemHeader systemHeader = CreateSystemHeader();

            //加2是 最后是CRC
            byte[] ip = new byte[] { 0x00 };
            int size = StructConverter.SizeOf(systemHeader) + ip.Length + 2;
            systemHeader.FrameLength = (ushort)size;

            using (MemoryStream stream = new MemoryStream(size))
            {
                using (BinaryWriter writer = new BinaryWriter(stream))
                {
                    writer.Write(StructConverter.StructToBytes(systemHeader));
                    writer.Write(ip);
                    writer.Write(new byte[] { 0, 0 });
                    return stream.ToArray();
                }
            }
        }

        public void Send_QueryData(byte[] originaldata, string hostnumber, string mac)
        {
            var data = CreateDataPacket();
            string vvv = Tools.ByteToString(data);
            logger.Error("cha xun:" + vvv + " hostnumber:" + hostnumber + " mac:" + mac);
            Send(data, hostnumber, mac);
        }
    }
}
