using SWModules;

namespace HWModules
{
    public class IridiumPosixSession : PosixSession
    {
        private readonly IridiumModem1 _iModem;

        public IridiumPosixSession(IridiumModem1 imodem)
            : base(imodem.IOPort)
        {
            _iModem = imodem;
            bSendExtraCRLF = true;
        }

        public bool IsConnected { get; protected set; }
        public bool hasHandler { get; protected set; }
        public int Connect(byte[] phonenumber)
        {


            //Hijack the serial port receive
            _iModem.ReleaseDataHandler();
            hasHandler = true;

            _iModem.dialDefaultRudics();
            //_iModem.dialNumber(phonenumber);

            int retval = 0;
            int resp = ExpectEither(120, "NO CARRIER", "CONNECT","ERROR");

            if (resp >= 0) // we got a response!
            {
                EngrLogger.Comment("IRIDIUM Modem Response: " + resp.ToString());
                //We got a no carrier
                if (resp == 0)
                {
                    //bummer give up after 1 try
                    EngrLogger.Comment("PS001 Connect: NO CARRIER received.");
                    retval = (int)PosixSession.ERROR.NOCARRIER;
                }
                else if (resp == 1)
                {
                    EngrLogger.Comment("Unit Connected! ");
                    IsConnected = true;
                    retval = SUCCESS;
                }
                else if (resp == 2)
                {
                    //error
                    EngrLogger.Comment("PS005 Connect: ERROR Received");
                    retval = (int) PosixSession.ERROR.NOCARRIER;
                }
            }
            else
            {
                EngrLogger.Comment("PS006 Connect: No Response from modem");
                retval = -2;
            } 

            //if we failed, set things back
            if (retval < 0)
                _iModem.AttachDataHandler();

            return retval;
        }

        public void Disconnect()
        {
            if (hasHandler)
            {
                _iModem.AttachDataHandler();
            }
                IsConnected = false;

        }

        ~IridiumPosixSession()
        {
            Disconnect();
        }
    }
}