using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace SampleCS
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        List<PhoneButton> myPhones = new List<PhoneButton>();

        static CIDR.Callback callback_pin = null;

        private void Form1_Shown(object sender, EventArgs e)
        {
            string di;
            int l;
            if (!CIDR.CIDR_GetInfo(out di, out l))
            {
                MessageBox.Show("Failed to load DLL!");
                Close();
            }

            AddLog("DLL Info: " + di);
            callback_pin = new CIDR.Callback(CIDR_Event);
            GC.KeepAlive(callback_pin);
            CIDR.CIDR_RegisterEvent(callback_pin, 5);
        }
 
        public void AddLog(string msg)
        {
            string dt = DateTime.Now.ToString("HH:mm:ss.fff");
            listBoxLog.Items.Add(dt + " " + msg);
            listBoxLog.SelectedIndex = listBoxLog.Items.Count - 1;
        }
        public void AddDescription(string msg)
        {
            string dt = DateTime.Now.ToString("HH:mm:ss.fff");
            listBoxDescription.Items.Add(dt + " " + msg);
            listBoxDescription.SelectedIndex = listBoxDescription.Items.Count - 1;
        }

        public void CIDR_Event(int line, string msg)
        {
            AddLog(line + ": " + msg);
        
            if (line==0) // system message
            {
                string di;
                int lines;
                CIDR.CIDR_GetInfo(out di, out lines);
                for (int i = myPhones.Count; i < lines; i++)
                {
                    PhoneButton pb = new PhoneButton();
                    pb.Parent = panelPhones;
                    pb.Visible = true;
                    pb.TelName = "Line " + (i + 1);
                    pb.TelState = LineState.NotInitialized;
                    pb.TelSave = SaveState.AutoSave;
                    pb.BackColor = SystemColors.Control;
                    pb.DoubleClick += new EventHandler(phone_DoubleClick);
                    myPhones.Add(pb);
                }
                ReArrangeButtons();
            }
            else    // line event
            {
                bool stopSave = false;
                string code = msg.Substring(0, 1);
                if (code == "Q")    // Device Disconnected    ارتباط دستگاه قطع است
                {
                    myPhones[line - 1].TelState = LineState.DeviceNotAvailable;
                    stopSave = true;
                    AddDescription("Device Disconnected, so Line "+line+"is not available");
                }
                else if (code == "X")   // Line Disconnected    خط قطغ است
                {
                    myPhones[line - 1].TelState = LineState.Disconnected;
                    stopSave = true;
                    AddDescription("Line "+line+" Disconnected");
                }
                else if (code == "F")   // Hook Off   گوشی برداشته شده
                {
                    myPhones[line - 1].TelState = LineState.HookedOff;
                    if (myPhones[line - 1].TelSave == SaveState.AutoSave)
                    {
                        SaveCall(line);
                    }
                    AddDescription("Line " + line + " Hooked Off");
                }
                else if (code == "N")   // Hook On گوشی گذاشته شده
                {
                    int p = msg.IndexOf("D");
                    int duration = Convert.ToInt32(msg.Substring(1, p - 1));
                    string dialed = msg.Substring(p + 1);

                    myPhones[line - 1].TelState = LineState.HookedOn;
                    stopSave = true;
                    AddDescription("Line " + line + " Hooked On after " + duration + " seconds; Dialed Numbers: " + dialed);
                }
                else if (code == "C")   // Caller ID    شماره تماس گیرنده به همراه تاریخ و ساعت اعلامی
                {
                    int p = msg.IndexOf(",");
                    string callerID = msg.Substring(1, p - 1);
                    string datetime = msg.Substring(p + 1);
                    if ((datetime.Length == 8) && (!datetime.Contains("00000000")))
                    {
                        string month = datetime.Substring(0, 2);
                        string day = datetime.Substring(2, 2);
                        string hour = datetime.Substring(4, 2);
                        string minute = datetime.Substring(6, 2);

                        datetime = month + "/" + day + " " + hour + ":" + minute;
                    }
                    else
                        datetime = "unknown";   // not sent from Service Provider

                    AddDescription("Line " + line + " Received Call From " + callerID + " @ " + datetime);
                }
                else if (code == "D")   // Dialed DTMF (single key)   تک کلید فشرده شده
                {
                    string key = msg.Substring(1, 1);
                    AddDescription("Line " + line + " Pressed Key: " + key);
                }
                else if (code == "R")   // Ring Started
                {
                    int ring = Convert.ToInt32(msg.Substring(1));
                    AddDescription("Line " + line + " Ring " + ring + " started");
                }

                if (stopSave && (myPhones[line-1].TelSave==SaveState.AutoSave))
                {
                    // stop save
                    CIDR.CIDR_SaveLine(line, "", "");
                }
                

            }

        }

        public void SaveCall(int line)
        {
            string fname = AppDomain.CurrentDomain.BaseDirectory + "تماسها" + "\\"
                + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")
                + " [" + line + "]" + ".mp3";
            // Save Line
            CIDR.CIDR_SaveLine(line, fname, "");
        }

        public void ReArrangeButtons()
        {
            if (myPhones.Count == 0)
                return;

            int step = panelPhones.ClientRectangle.Width / myPhones.Count;
            int w = step - 10;
            int x = (step - w) / 2;
            int h = panelPhones.ClientRectangle.Height - 10;
            int y = (panelPhones.ClientRectangle.Height - h) / 2;

            for (int i = 0; i < myPhones.Count; i++)
            {
                myPhones[i].SetBounds(x, y, w, h);
                x += step;
            }
        }

        int lastPlay = 0;
        private void phone_DoubleClick(object sender, EventArgs e)
        {
            if (lastPlay != 0)
                myPhones[lastPlay-1].BackColor = SystemColors.Control;

            if (sender is PhoneButton)
            {
                int l = Convert.ToInt32(((PhoneButton)sender).TelName.Substring(4).Trim());
                bool isOK = (CIDR.CIDR_PlayLine(l) != 0);
                AddDescription("Playing Line " + l + ": " + (isOK ? "OK" : "Failed"));
                if (isOK)
                {
                    myPhones[l-1].BackColor = Color.Aqua;
                    lastPlay = l;
                }
            }
            else
            {
                CIDR.CIDR_PlayLine(0);
                lastPlay = 0;
                AddDescription("Stop Playing");
            }
        }

        private void panelPhones_Resize(object sender, EventArgs e)
        {
            ReArrangeButtons();
        }

        private void buttonGetInfo_Click(object sender, EventArgs e)
        {
            MessageBox.Show(CIDR.CIDR_InfoStr());
        }
    }
}
