using Helpers.Log;
using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Xml;
using System.Xml.Serialization;

public partial class app_custom_screens_IHConfiguration_data_sources_configuration_v2_PLCConfiguration : Page
{
    private ILog logger = Logger.GetLogger(MethodBase.GetCurrentMethod().DeclaringType.Name);

    private class PLCConfig
    {
        public Dictionary<String, Object> Values { get; set; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        string action = Request.Form["action"];

        if (action != null)
        {
            switch (action.ToUpper())
            {
                case "SERIALIZECONFIGURATION":
                    this.SerializeConfiguration(); 
                    break; 
                case "DESERIALIZECONFIGURATION":
                    this.DeserializeConfiguration(); 
                    break; 
            }
        }
    }

    private void SerializeConfiguration()
    {
        System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
        try
        {
            PLCConnectionConfiguration PLCConnConfig = new PLCConnectionConfiguration();

            string data = Request.Form["data"]; 
            this.logger.Debug("     - Deserializing Config.");
            PLCConfig plcConfig = jss.Deserialize<PLCConfig>(data);
            this.logger.Debug("     - Deserialized Complete.");

            int connectionType;
            PLCConnConfig.ConnectionType = (Int32.TryParse((string)plcConfig.Values["CONNECTIONTYPE"], out connectionType)) ? connectionType : PLCConnConfig.ConnectionType;
            PLCConnConfig.EntryPoint = (!String.IsNullOrEmpty((string)plcConfig.Values["ENTRYPOINT"])) ? (string)plcConfig.Values["ENTRYPOINT"] : PLCConnConfig.EntryPoint;
            int cpuRack;
            PLCConnConfig.CpuRack = (Int32.TryParse((string)plcConfig.Values["CPURACK"], out cpuRack)) ? cpuRack : PLCConnConfig.CpuRack;
            int cpuSlot;
            PLCConnConfig.CpuSlot = (Int32.TryParse((string)plcConfig.Values["CPUSLOT"], out cpuSlot)) ? cpuSlot : PLCConnConfig.CpuSlot;
            int cpuMPI;
            PLCConnConfig.CpuMpi = (Int32.TryParse((string)plcConfig.Values["CPU_MPI"], out cpuMPI)) ? cpuMPI : PLCConnConfig.CpuMpi;
            PLCConnConfig.CpuIP = (!String.IsNullOrEmpty((string)plcConfig.Values["IPADDRESS"])) ? (string)plcConfig.Values["IPADDRESS"] : PLCConnConfig.CpuIP;
            int port;
            PLCConnConfig.Port = (Int32.TryParse((string)plcConfig.Values["PORT"], out port)) ? port : PLCConnConfig.Port;
            int busSpeed;
            PLCConnConfig.BusSpeed = (Int32.TryParse((string)plcConfig.Values["MPI_DP_SPEED"], out busSpeed)) ? busSpeed : PLCConnConfig.BusSpeed;
            int timeoutIPConnect;
            PLCConnConfig.TimeoutIPConnect = (Int32.TryParse((string)plcConfig.Values["TIMEOUTIPCONNECT"], out timeoutIPConnect)) ? timeoutIPConnect : PLCConnConfig.TimeoutIPConnect;
            int timeout;
            PLCConnConfig.Timeout = (Int32.TryParse((string)plcConfig.Values["TIMEOUT"], out timeout)) ? timeout : PLCConnConfig.Timeout;
            int lokalMPI;
            PLCConnConfig.LokalMpi = (Int32.TryParse((string)plcConfig.Values["LOKALMPI"], out lokalMPI)) ? lokalMPI : PLCConnConfig.LokalMpi;
            PLCConnConfig.ComPort = (!String.IsNullOrEmpty((string)plcConfig.Values["COMPORT"])) ? ((((string)plcConfig.Values["COMPORT"]).StartsWith("COM", true, System.Globalization.CultureInfo.CurrentCulture)) ? ((string)plcConfig.Values["COMPORT"]) : "COM" + ((string)plcConfig.Values["COMPORT"])) : PLCConnConfig.ComPort;
            PLCConnConfig.ComPortSpeed = (!String.IsNullOrEmpty((string)plcConfig.Values["COMPORTSPEED"])) ? (string)plcConfig.Values["COMPORTSPEED"] : PLCConnConfig.ComPortSpeed;
            PLCConnConfig.ComPortParity = (!String.IsNullOrEmpty((string)plcConfig.Values["COMPORTPARITY"])) ? ((string)plcConfig.Values["COMPORTPARITY"]).ToCharArray()[0] : PLCConnConfig.ComPortParity;
            bool netlinkReset;
            PLCConnConfig.NetLinkReset = (Boolean.TryParse((string)plcConfig.Values["NETLINKRESET"], out netlinkReset)) ? netlinkReset : PLCConnConfig.NetLinkReset;

            XmlSerializer ser = new XmlSerializer(typeof(PLCConnectionConfiguration));
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");

            String xml;
            XmlWriterSettings settings = new XmlWriterSettings()
            {
                OmitXmlDeclaration = true,
            };
            using (StringWriter textWriter = new StringWriter())
            {
                using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
                {
                    ser.Serialize(xmlWriter, PLCConnConfig, ns);
                }
                xml = textWriter.ToString();
                xml = xml.Replace("\r\n", "");
            }

            Response.Write(jss.Serialize(new { status = "OK", value = xml }));
        }
        catch (Exception ex)
        {
            Response.Write(jss.Serialize(new { status = "FAILED", message = ex.Message.ToString() }));
        }
    }

    private void DeserializeConfiguration()
    {
        System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
        try
        {
            string xml = Request.Form["configurationXML"];
            xml = HttpUtility.UrlDecode(xml); 
            PLCConnectionConfiguration PLCConnConfig = new PLCConnectionConfiguration();

            XmlSerializer ser = new XmlSerializer(typeof(PLCConnectionConfiguration));

            StringReader rdr = new StringReader(xml);
            PLCConnConfig = (PLCConnectionConfiguration)ser.Deserialize(rdr); 

            Response.Write(jss.Serialize(new { status = "OK", value = PLCConnConfig }));
        }
        catch (Exception ex)
        {
            Response.Write(jss.Serialize(new { status = "FAILED", message = ex.Message.ToString() }));
        }
    }
}