using GatewayTool.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace GatewayTool.Protocols
{
    public class DTUProtocol : GatewayProtocolBase
    {
        /// <summary>
        /// 读DTU系统状态
        /// </summary>
        /// <returns></returns>
        public byte[] PackReadDTUSystemState()
        {
            byte[] data = { 0x02 };
            return Pack(data);
        }

        /// <summary>
        /// 读DTU设备配置
        /// </summary>
        /// <returns></returns>
        public byte[] PackReadDTUDeviceConfig()
        {
            byte[] data = { 0x03 };
            return Pack(data);
        }

        /// <summary>
        /// 写DTU设备配置
        /// </summary>
        /// <param name="json">json配置字符串</param>
        /// <returns></returns>
        public byte[] PackWriteDTUDeviceConfig(string json)
        {
            byte[] data = { 0x04 };
            return PackJson(data, json);
        }

        /// <summary>
        /// 准备升级固件
        /// </summary>
        /// <returns></returns>
        public byte[] PackPrepareToUpgrade()
        {
            byte[] data = { 0x05 };
            return Pack(data);
        }

        /// <summary>
        /// 解析读DTU系统状态
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public DTUSystemState UnpackReadDTUSystemState(byte[] data)
        {
            try
            {
                byte[] data2 = Unpack(data);
                string json = Encoding.ASCII.GetString(data2);
                return JsonConvert.DeserializeObject<DTUSystemState>(json);
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 解析读DTU设备配置
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public DTUConfig UnpackReadDTUDeviceConfig(byte[] data)
        {
            try
            {
                byte[] data2 = Unpack(data);
                string json = Encoding.ASCII.GetString(data2);
                return JsonConvert.DeserializeObject<DTUConfig>(json);
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 解析写DTU设备配置
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public bool UnpackWriteDTUDeviceConfig(byte[] data)
        {
            try
            {
                byte[] data2 = Unpack(data);
                return data2[0] == 0x01;
            }
            catch
            {
                return false;
            }
        }
    }
}