using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace VR2
{
    /*
    ===========================================================================================================================

      T EXT  AUTH TRK  MM/DD STT.TIME DURATION FG DIALED DIGIT       ACCOUNT CODE MCNT     COST CLIP NUMBER  CLIP NAME         
    ===========================================================================================================================
      1 3201      8504 03/30 09:07:58 00:00:00 IR 0100105327                               0.00 0310100805   2001          
      1 3201      8504 03/30 09:07:58 00:00:05 IA 0100105327                               0.00 0310100805   2001              
      1 3201      8504 03/30 09:08:03 00:00:23 I  0100105327                               0.00 0310100805   2001              
      1 3201      8504 03/30 11:06:06 00:00:00 IR 0100105327                               0.00 0310100805   2001              
      1 3201      8504 03/30 11:06:06 00:00:09 IA 0100105327                               0.00 0310100805   2001              
      1 3201      8504 03/30 11:06:15 00:00:21 I  0100105327                               0.00 0310100805   2001              


        500       842  01/04 02:25:30 00:00:02 A  0100100889                               0.00 686958482474                   

        264       835  01/07 14:30:43 00:00:25 O  0836586747                               0.00                                                                

        264       835  01/07 14:37:45 00:00:00 O  0836586747                               0.00                                


        264       835  01/07 14:37:45 00:00:00 O  0836586747                               0.00                     

        265       835  01/07 14:42:40 00:01:35 O  0110124205                               0.00                                

        264       836  01/07 14:43:00 00:01:16 O  0836586747                               0.00                                

        264       835  01/07 14:46:43 00:00:30 O  0836586747                               0.00                                
        264       835  01/07 14:51:01 00:00:00 O  0110124205                               0.00                                

        264       835  01/07 14:51:01 00:00:00 O  0110124205                               0.00                                
        264       835  01/07 14:51:22 00:01:10 O  0836586747                               0.00  
                                                            

        265       835  01/07 14:55:53 00:00:02 O  0836586747                               0.00                                
        265       835  01/07 14:55:58 00:00:01 O  0836586747                               0.00  
                       
        265       835  01/07 14:56:18 00:00:03 O  0836586747#                              0.00                                

        265       835  01/07 14:56:24 00:00:01 O  0836586747#                              0.00                                


        265       835  01/07 14:56:37 00:01:02 O  0836586747#                              0.00                                
        264       835  01/07 15:12:25 00:00:13 OT 0836272475#                              0.00                                 
    */
    public class SamsungCDR
    {
        public DateTime ReceivedTime;
        public string T;
        public string EXT;
        public string AUTH;
        public string TRK;
        public string MM_DD;
        public string STT_TIME;
        public string DURATION;
        public string FG;
        public string DIALED_DIGIT;
        public string ACCOUNT;
        public string CODE;
        public string MCNT;
        public string COST;
        public string CLIP_NUMBER;
        public string CLIP_NAME;

        public string LogString()
        {
            string s = "T:" + T + " ";
            s += "EXT:" + EXT + " ";
            s += "AUTH:" + AUTH + " ";
            s += "TRK:" + TRK + " ";
            s += "MM_DD:" + MM_DD + " ";
            s += "STT_TIME:" + STT_TIME + " ";
            s += "DURATION:" + DURATION + " ";
            s += "FG:" + FG + " ";
            s += "DIALED_DIGIT:" + DIALED_DIGIT + " ";
            s += "ACCOUNT:" + ACCOUNT + " ";
            s += "CODE:" + CODE + " ";
            s += "MCNT:" + MCNT + " ";
            s += "COST:" + COST + " ";
            s += "CLIP_NUMBER:" + CLIP_NUMBER + " ";
            s += "CLIP_NAME:" + CLIP_NAME + " ";
            return s;
        }
    }

    public class SamsungCDRProcess
    {
        public string SamsungPBXIPAddr;
        public ushort SamsungPBXPort;
        public Thread workThread;
        public bool isExiting;
        public TcpClient tcpclient;
        public List<SamsungCDR> cdrList;
        public VR2Manager vr2m;

        public SamsungCDRProcess()
        {
            isExiting = false;
            cdrList = new List<SamsungCDR>();
            vr2m = null;
        }

        public void StartProcess()
        {
            isExiting = false;
            workThread = new Thread(Run);
            workThread.Start(this);
        }

        public void StopProcess()
        {
            isExiting = true;
            workThread.Join();
            workThread = null;
        }

        static void Run(object obj)
        {
            SamsungCDRProcess cdr_process = (SamsungCDRProcess)obj;
            cdr_process.tcpclient = new TcpClient();
            try
            {
                cdr_process.tcpclient.Connect(cdr_process.SamsungPBXIPAddr, cdr_process.SamsungPBXPort);
            }
            catch (SocketException e)
            {
                VRAPIASM.VRAPIEnv.Log(1, e.ToString());
                cdr_process.isExiting = true;
                return;
            }

            VRAPIASM.VRAPIEnv.Log(4, "SamsungCDRProcess connected to " + cdr_process.SamsungPBXIPAddr + ":" + cdr_process.SamsungPBXPort.ToString());

            Byte[] data = new Byte[4096];
            NetworkStream stream = cdr_process.tcpclient.GetStream();
            while (!cdr_process.isExiting && cdr_process.tcpclient.Connected)
            {
                if (stream.DataAvailable)
                {
                    String responseData = String.Empty;
                    try
                    {
                        Int32 bytes = stream.Read(data, 0, data.Length);
                        responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                        VRAPIASM.VRAPIEnv.Log(4, "Samsung cdr:[" + responseData + "]");

                        char[] delimiters = new char[] { '\r', '\n' };
                        string[] lines = responseData.Split(delimiters, StringSplitOptions.None);
                        for (int i = 0; i < lines.Length; i++)
                        {
                            string line = lines[i];

                            if (line.Length > 0)
                            {
                                if (cdr_process.vr2m != null && VRAPIASM.VRAPIEnv.IsLicensed() != 0)
                                {
                                    cdr_process.vr2m.SendEvent(IntPtr.Zero, "CDRRawData", line);
                                }

                                if (line.Contains("====")) continue;//skip 
                                if (line.Contains("DIALED DIGIT")) continue;//skip 
                                if (line.Contains("SMDR REPORT FOR")) continue;//skip 
                                if (line.Length < 20) continue; //not valid line
                                SamsungCDR cdr = new SamsungCDR();

                                cdr.ReceivedTime = DateTime.Now;
                                cdr.T = line.Substring(0, 3).Trim();
                                cdr.EXT = line.Substring(4, 4).Trim();
                                cdr.AUTH = line.Substring(9, 4).Trim();
                                cdr.TRK = line.Substring(14, 4).Trim();
                                cdr.MM_DD = line.Substring(19, 5).Trim();
                                cdr.STT_TIME = line.Substring(25, 8).Trim();
                                cdr.DURATION = line.Substring(34, 8).Trim();
                                cdr.FG = line.Substring(43, 2).Trim();
                                cdr.DIALED_DIGIT = line.Substring(46, 18).Trim();
                                cdr.ACCOUNT = line.Substring(65, 7).Trim();
                                cdr.CODE = line.Substring(73, 4).Trim();
                                cdr.MCNT = line.Substring(78, 8).Trim();
                                cdr.COST = line.Substring(87, 4).Trim();
                                cdr.CLIP_NUMBER = line.Substring(92, 12).Trim();
                                cdr.CLIP_NAME = line.Substring(105).Trim();

                                VRAPIASM.VRAPIEnv.Log(4, cdr.LogString());

                                lock(cdr_process)
                                {
                                    cdr_process.cdrList.Add(cdr);
                                }
                            }
                        }
                    }
                    catch (SocketException e)
                    {
                        VRAPIASM.VRAPIEnv.Log(1, e.ToString());
                    }
                }
                else
                {
                    Thread.Sleep(200);
                }
            }
            // Close everything.
            stream.Close();
            cdr_process.tcpclient.Close();
            cdr_process.tcpclient = null;
            cdr_process.isExiting = true;

            VRAPIASM.VRAPIEnv.Log(4, "SamsungCDRProcess Disconnected to " + cdr_process.SamsungPBXIPAddr + ":" + cdr_process.SamsungPBXPort.ToString());

        }

    }
}
