using System;
using System.Collections.Generic;
using System.Text;

namespace CeFComTestApplication
{
    public class SendToPrinter
    {

        public string Send(string _protocol, string _ip, string _logLevel, string _encoding, int _port, string _cmdIn)
        {
            Custom.CeFCom.CeFCom comunicationElement = new Custom.CeFCom.CeFCom();

            string sRes = "";

            try
            {

                comunicationElement.CurrentProtocol = (Custom.CeFCom.Enums.ProtocolTypeEnum)Enum.Parse(typeof(Custom.CeFCom.Enums.ProtocolTypeEnum), _protocol);
                comunicationElement.LogLevel = (Custom.CeFCom.Enums.LogLevelEnum)Enum.Parse(typeof(Custom.CeFCom.Enums.LogLevelEnum), _logLevel);
                comunicationElement.EncodingType = (Custom.CeFCom.PrinterCodePages.EncodingTypeEnum)Enum.Parse(typeof(Custom.CeFCom.PrinterCodePages.EncodingTypeEnum), _encoding);

                if (!string.IsNullOrEmpty(_cmdIn) && _cmdIn.Length >= 4)
                {
                    string cmd = _cmdIn.Substring(0, 4);
                    string cmdResponse = string.Empty;
                    int openCommandResult = int.MinValue;

                    openCommandResult = comunicationElement.CEFOpenEth(_ip, _port);

                    sRes += "OPEN: " + LogCmdResult("OPEN", openCommandResult);

                    //WRITE, READ AND CLOSE ONLY IF OPEN METHOD IS OK
                    if (openCommandResult == (int)Custom.CeFCom.Enums.ErrorListEnum.OPERATION_OK)
                    {

                        sRes += "WRITE: " + LogCmdResult("WRITE", comunicationElement.CEFWrite(_cmdIn));

                        sRes += "READ: " + LogCmdResult("READ", comunicationElement.CEFRead(cmd, out cmdResponse));
                        sRes += "RES: " + cmdResponse;

                        sRes += "CLOSE: " + LogCmdResult("CLOSE", comunicationElement.CEFClose());


                    }
                }
                else
                    sRes += "ERROR: " + "Invalid Command";

            }
            catch (Exception e)
            {
                sRes += "ERROR: " + e.Message;
            }

            return sRes;


        }

        private string LogCmdResult(string step, int commandResult)
        {
            string messageToLog = Enum.GetName(typeof(Custom.CeFCom.Enums.ErrorListEnum), commandResult);
            messageToLog = string.Format("{0}:{1}{2}{3}", step, "\t", messageToLog, Environment.NewLine);
            return messageToLog;
        }


    }
}

