using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Xml;
using System.Data.SqlClient;
using System.IO;
using System.Diagnostics;
using VR2;

namespace VR2ManagerClient
{
    public partial class ComplexSearch : Form
    {
        public int maxChanNum;
        public VR2.DBServerSetting db_set;

        public ComplexSearch()
        {
            InitializeComponent();
        }

        private void ComplexSearch_Load(object sender, EventArgs e)
        {
            mtbCallerIP.ValidatingType = typeof(System.Net.IPAddress);
            mtbCalledIP.ValidatingType = typeof(System.Net.IPAddress);

            cbLineNo.Items.Add("All");
            for (int i = 0; i < maxChanNum; i++)
            {
                int lineno = i+1;
                cbLineNo.Items.Add(lineno.ToString());
            }
            cbLineNo.SelectedIndex = 0;

            cbDuration.Items.Add(">");
            cbDuration.Items.Add("=");
            cbDuration.Items.Add("<");
            cbDuration.SelectedIndex = 0;

            cbNoOfRings.Items.Add("Not Specified");
            for (int i = 0; i < 10; i++)
            {
                int lineno = i + 1;
                cbNoOfRings.Items.Add("Within " + lineno.ToString());
            }
            cbNoOfRings.SelectedIndex = 0;

            dtpStartDate.Value = DateTime.Now.AddDays(-5);
            dtpStartDate.Checked = false;
            dtpEndDate.Checked = false;
        }

        string stripOffSpace(string s)
        {
            string s1 = "";
            for (int i = 0; i < s.Length; i++)
            {
                if (s[i] != ' ')
                {
                    s1 += s[i];
                }
            }
            return s1;
        }


        public string DateTimeToStr(DateTime dt)
        {
            string sret = "";
            sret += dt.Year.ToString() + "-" + dt.Month.ToString() + "-" + dt.Day.ToString() + " ";
            sret += dt.Hour.ToString() + ":" + dt.Minute.ToString() + ":" + dt.Second.ToString();

            sret = "convert(datetime, '" + sret + "', 120)";

            return sret;
        }


        public string getFileExtension(string fileName)
        {
            /*
            string extension = "";
            char[] arr = fileName.ToCharArray();
            int index = 0;
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i] == '.')
                {
                    index = i; //get the last dot in the string 
                }
            }
            for (int x = index + 1; x < arr.Length; x++)//build the new string 
            {
                extension = extension + arr[x];
            }

            return extension;
            */
            FileInfo fi = new FileInfo(fileName);
            return fi.Extension;
        }

        public string GetFileNameOnly(string sFileName)
        {
            FileInfo fi = new FileInfo(sFileName);
            string ext = fi.Extension;
            string fn = fi.Name;
            string fn1 = "";
            for (int i = 0; i < fn.Length - ext.Length; i++)
            {
                fn1 += fn[i];
            }
            return fn1;
        }

        public string MakeSQL()
        {
            bool cnd = false;

            string commandStr = "SELECT ChanID, Succeed, CallerIP, CallerID, CallerName, CalleeIP, CalleeID, CalleeName, TimeInit, TimeBegin, TimeEnd, Duration, RecordPath, UniqueID, DTMF, DIR FROM " + db_set.CallLogTableName + " WHERE ";

            if (cbLineNo.SelectedIndex == 0)
            {
                //all
            }
            else
            {
                if (cnd) commandStr += "AND ";
                commandStr += "ChanID = " + cbLineNo.SelectedIndex.ToString() + " ";
                cnd = true;
            }

            if (tbCallerName.Text.Length > 0)
            {
                if (cnd) commandStr += "AND ";
                commandStr += "CallerName LIKE '%" + tbCallerName.Text + "%' ";
                cnd = true;
            }

            if (tbCallerNumber.Text.Length > 0)
            {
                if (cnd) commandStr += "AND ";
                commandStr += "CallerID LIKE '%" + tbCallerNumber.Text + "%' ";
                cnd = true;
            }

            //MessageBox.Show(mtbCallerIP.Text);

            string ipAddr = stripOffSpace(mtbCallerIP.Text);

            if (ipAddr != "...")
            {
                IPAddress ipAddress;
                if (IPAddress.TryParse(ipAddr, out ipAddress))
                {
                    //valid ip
                    //MessageBox.Show(ipAddress.ToString());
                    if (cnd) commandStr += "AND ";
                    commandStr += "CallerIP LIKE '%" + ipAddress.ToString() + "%' ";
                    cnd = true;
                }
                else
                {
                    //invalid ip
                    MessageBox.Show("Invalid caller ip address! " + ipAddress.ToString());
                    return "";
                }
            }
            else
            {
                //MessageBox.Show("Caller ip not set");
            }


            if (tbCalledName.Text.Length > 0)
            {
                if (cnd) commandStr += "AND ";
                commandStr += "CalleeName LIKE '%" + tbCalledName.Text + "%' ";
                cnd = true;
            }

            if (tbCalledNumber.Text.Length > 0)
            {
                if (cnd) commandStr += "AND ";
                commandStr += "CalleeID LIKE '%" + tbCalledNumber.Text + "%' ";
                cnd = true;
            }

            //MessageBox.Show(mtbCallerIP.Text);

            ipAddr = stripOffSpace(mtbCalledIP.Text);

            if (ipAddr != "...")
            {
                IPAddress ipAddress;
                if (IPAddress.TryParse(ipAddr, out ipAddress))
                {
                    //valid ip
                    //MessageBox.Show(ipAddress.ToString());
                    if (cnd) commandStr += "AND ";
                    commandStr += "CalleeIP LIKE '%" + ipAddress.ToString() + "%' ";
                    cnd = true;
                }
                else
                {
                    //invalid ip
                    MessageBox.Show("Invalid caller ip address! " + ipAddress.ToString());
                    return "";
                }
            }
            else
            {
                //MessageBox.Show("Caller ip not set");
            }

            ipAddr = stripOffSpace(mtbDuration.Text);
            if (ipAddr != "::")
            {
                //get seconds
                int sec = 0;
                char[] delimiters = new char[] { ':' };
                string[] ss = ipAddr.Split(delimiters, StringSplitOptions.None);
                if (ss != null)
                {
                    if (ss[0] != "")
                    {
                        sec += Convert.ToInt32(ss[0]) * 3600;
                    }
                    if (ss[1] != "")
                    {
                        sec += Convert.ToInt32(ss[1]) * 60;
                    }
                    if (ss[2] != "")
                    {
                        sec += Convert.ToInt32(ss[2]);
                    }
                }

                if (cnd) commandStr += "AND ";
                commandStr += "Duration ";
                if(cbDuration.SelectedIndex == 0)
                    commandStr += "> ";
                else if (cbDuration.SelectedIndex == 1)
                    commandStr += "= ";
                else if (cbDuration.SelectedIndex == 2)
                    commandStr += "< ";
                commandStr += sec.ToString() + " ";
                cnd = true;
            }
            else
            {
                //not input anything
            }

            if (cbNoOfRings.SelectedIndex > 0)
            {
                int sec = cbNoOfRings.SelectedIndex * 6;

                //I don't know how to do sql query to select the difference between two date column

            }

            if (dtpStartDate.Checked)
            {
                if (cnd) commandStr += "AND ";
                commandStr += "TimeInit >= " + DateTimeToStr(dtpStartDate.Value) + " ";
                cnd = true;
            }

            if (dtpEndDate.Checked)
            {
                if (cnd) commandStr += "AND ";
                commandStr += "TimeEnd <= " + DateTimeToStr(dtpEndDate.Value) + " ";
                cnd = true;
            }

            if (tbDTMF.Text.Length > 0)
            {
                if (cnd) commandStr += "AND ";
                commandStr += "DTMF LIKE '%" + tbDTMF.Text + "%' ";
                cnd = true;
            }

            if (cbIncoming.Checked)
            {
                if (cnd) commandStr += "AND ";
                commandStr += "DIR = 0 ";
                cnd = true;
            }

            if (cbOutgoing.Checked)
            {
                if (cnd) commandStr += "AND ";
                commandStr += "DIR = 1 ";
                cnd = true;
            }

            if (cbNoAnswer.Checked)
            {
                if (cnd) commandStr += "AND ";
                commandStr += "Succeed = 0 ";
                cnd = true;
            }

            if (cbAudio.Checked)
            {
                if (cnd) commandStr += "AND ";
                commandStr += "RecordPath <> '' AND RecordPath IS NOT NULL";
                cnd = true;
            }

            if (!cnd)
            {
                commandStr = commandStr.Substring(0, commandStr.Length - 6); //remove WHERE
            }

            return commandStr;
        }

        void RefreshDataGridView()
        {
            btnSearch_Click(null, null);
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {

            string sql = MakeSQL();

            if (sql != "")
            {
                //MessageBox.Show(sql);

                try
                {

                    if (db_set.ConnectDB())
                    {
                        string strCon = db_set.GetConnStr();
                        string strSQL = sql;
                        SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, strCon);
                        SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
                        BindingSource dbBindSource = new BindingSource();

                        // Populate a new data table and bind it to the BindingSource.
                        DataTable table = new DataTable();
                        table.Locale = System.Globalization.CultureInfo.InvariantCulture;
                        dataAdapter.Fill(table);

                        dbBindSource.DataSource = table;

                        // Resize the DataGridView columns to fit the newly loaded content.
                        dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);

                        // you can make it grid readonly.
                        dataGridView1.ReadOnly = true;

                        // finally bind the data to the grid
                        dataGridView1.DataSource = dbBindSource;

                        dataGridView1.Columns["TimeInit"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
                        dataGridView1.Columns["TimeBegin"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
                        dataGridView1.Columns["TimeEnd"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";


                        db_set.DisconnectDB();


                        SetStasticData();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString() + " " + sql);
                }

            }


        }

        void SetStasticData()
        {
            int totalFiles, totalDuration;
            long totalSize;

            totalFiles = 0;
            totalDuration = 0;
            totalSize = 0;

            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                if (dataGridView1.Rows[i].Cells[11].Value == null) continue;

                string dur = dataGridView1.Rows[i].Cells[11].Value.ToString();
                string fn = dataGridView1.Rows[i].Cells[12].Value.ToString();
                string rid = dataGridView1.Rows[i].Cells[13].Value.ToString();

                if (fn.Length > 0)
                    totalFiles++;

                if (dur.Length > 0)
                    totalDuration += Convert.ToInt32(dur);

                if (File.Exists(fn))
                {
                    FileInfo f = new FileInfo(fn);
                    totalSize += f.Length;
                }

            }

            tbTotalFiles.Text = totalFiles.ToString();
            tbTotalDuration.Text = totalDuration.ToString() + " Sec.";
            tbTotalSize.Text = totalSize.ToString();
        }



        private void btnRecFolder_Click(object sender, EventArgs e)
        {
            string rootFolder = "";

            string xmlFileName = Application.StartupPath + "\\VR2Config.xml";

            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(xmlFileName);
            }
            catch (Exception)
            {
                MessageBox.Show("Failed to load " + xmlFileName);
                return;
            }

            XmlElement root = xmlDoc.DocumentElement;


            XmlNode tmpNode = root.SelectSingleNode("//VoiceRecorder/AudioRootFolder");
            if (tmpNode != null)
            {
                rootFolder = tmpNode.InnerText;

                if (rootFolder.Length > 0)
                {
                    if (!System.IO.Directory.Exists(rootFolder))
                    {
                        MessageBox.Show(rootFolder + " doesn't exist, so it can't be openned");
                    }
                    else
                    {
                        Process.Start(rootFolder);
                    }
                }
                else
                {
                    MessageBox.Show("AudioRootFolder is null in XML config.");
                }
            }
            else
            {
                MessageBox.Show("AudioRootFolder is null in XML config.");
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count == 0)
            {
                MessageBox.Show("Error: No row selected. Please select rows to delete.");
                return;
            }

            if (MessageBox.Show("Are you sure you want delete those selected records from database and their related sound files?", "Delete Comfirmation", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                if (db_set.ConnectDB())
                {
                    for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
                    {
                        int idx = dataGridView1.SelectedRows[i].Cells[0].RowIndex;
                        string rid = dataGridView1.Rows[idx].Cells[13].Value.ToString();
                        string fn = dataGridView1.Rows[idx].Cells[12].Value.ToString();
                        DeleteRecord(rid, fn);
                    }
                    db_set.DisconnectDB();
                    RefreshDataGridView();
                }
                else
                {
                    MessageBox.Show("Cannot connect to database!", "Error");
                }
            }
        }

        private void btnDeleteAll_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want delete all those records listed from database and their related sound files?", "Delete All Comfirmation", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                if (db_set.ConnectDB())
                {
                    for (int i = 0; i < dataGridView1.Rows.Count; i++)
                    {
                        string rid = dataGridView1.Rows[i].Cells[13].Value.ToString();
                        string fn = dataGridView1.Rows[i].Cells[12].Value.ToString();
                        DeleteRecord(rid, fn);
                    }
                    db_set.DisconnectDB();
                    RefreshDataGridView();
                }
                else
                {
                    MessageBox.Show("Cannot connect to database!", "Error");
                }
            }
        }

        private void btnPlay_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 1)
            {
                MessageBox.Show("Error: Please only select one row to play.");
                return;
            }

            if (dataGridView1.SelectedRows.Count == 0)
            {
                MessageBox.Show("Error: No row selected. Please select one row to play.");
                return;
            }

            int rowIndex = dataGridView1.SelectedRows[0].Cells[0].RowIndex;

            playRow(rowIndex);
        }

        bool DeleteRecord(string rid, string fn)
        {
            try
            {
                if (File.Exists(fn))
                    File.Delete(fn);
            }
            catch (Exception)
            {
            }

            string commandStr = "DELETE FROM " + db_set.CallLogTableName + " WHERE UniqueID = '" + rid + "'";

            SqlCommand myComm = new SqlCommand(commandStr, db_set.myConn);
            myComm.CommandText = commandStr;
            if (myComm.ExecuteNonQuery() == 1)
            {
                return true;
            }
            else
            {
                return false;
            }

        }


        void playRow(int rowIndex)
        {
            string tempPath = "c:\\temp\\vr2\\";
            string fn = "";

            string cmd1, cmd2, cmd3;
            //string tempPath = System.IO.Path.GetTempPath();

            if (!System.IO.Directory.Exists("c:\\temp"))
                System.IO.Directory.CreateDirectory("c:\\temp");

            if (!System.IO.Directory.Exists(tempPath))
                System.IO.Directory.CreateDirectory(tempPath);

            if (tempPath[tempPath.Length - 1] == '\\')
            {
                cmd1 = tempPath + "*.wav";
                cmd2 = tempPath + "*.mp3";
                cmd3 = tempPath + "*.gsm";
            }
            else
            {
                cmd1 = tempPath + "\\" + "*.wav";
                cmd2 = tempPath + "\\" + "*.mp3";
                cmd3 = tempPath + "\\" + "*.gsm";
            }

            try
            {
                File.Delete(cmd1);
                File.Delete(cmd2);
                File.Delete(cmd3);
            }
            catch (Exception)
            {
            }

            //if (DataViewType == 0) return;

            try
            {

                fn = dataGridView1.Rows[rowIndex].Cells[12].Value.ToString();

                if (fn.Length == 0)
                {
                    MessageBox.Show("Recording file name is null.");
                    return;
                }

                string fname = GetFileNameOnly(fn);
                string fext = getFileExtension(fn);
                fn = fn.Substring(0, fn.Length - fname.Length - fext.Length);

                int n = 1;
                while (true)
                {
                    string fn1 = fn + fname + "-" + n.ToString() + fext;
                    FileInfo fi = new FileInfo(fn1);
                    if (fi.Exists)
                    {
                        n++;
                    }
                    else
                    {
                        break;
                    }
                }

                if (n > 1)
                {
                    SelectWavForm dlg = new SelectWavForm();
                    dlg.f_path = fn;
                    dlg.f_name = fname;
                    dlg.f_ext = fext;
                    dlg.file_num = n;
                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        int sel = dlg.idx_sel;
                        if (sel == 0)
                            fn = fn + fname + fext;
                        else
                            fn = fn + fname + "-" + sel.ToString() + fext;
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    fn = fn + fname + fext;
                }

                if (fext == ".wzp")
                {
                    string fnwav;

                    if (tempPath[tempPath.Length - 1] == '\\')
                    {
                        fnwav = tempPath + fname + ".wav";
                    }
                    else
                    {
                        fnwav = tempPath + "\\" + fname + ".wav";
                    }
                    GTAPIASM.GTEncode.FileDecode(fn, fnwav);
                    fn = fnwav;
                }
                else if (fext == ".mzp")
                {
                    string fnwav;
                    if (tempPath[tempPath.Length - 1] == '\\')
                    {
                        fnwav = tempPath + fname + ".mp3";
                    }
                    else
                    {
                        fnwav = tempPath + "\\" + fname + ".mp3";
                    }
                    GTAPIASM.GTEncode.FileDecode(fn, fnwav);
                    fn = fnwav;
                }
                else if (fext == ".gzp")
                {
                    string fnwav;

                    if (tempPath[tempPath.Length - 1] == '\\')
                    {
                        fnwav = tempPath + fname + ".gsm";
                    }
                    else
                    {
                        fnwav = tempPath + "\\" + fname + ".gsm";
                    }
                    GTAPIASM.GTEncode.FileDecode(fn, fnwav);
                    fn = fnwav;
                }

                if (File.Exists(fn))
                {

                    System.Diagnostics.Process Proc = new System.Diagnostics.Process();
                    Proc.StartInfo.FileName = fn;
                    try
                    {
                        Proc.Start();
                    }
                    catch (Exception ep)
                    {
                        MessageBox.Show("Error when playing file:(" + fn + ")\r\n" + ep.ToString());
                    }
                }
                else
                {
                    MessageBox.Show(fn + " doesn't exist any more on the disk.");
                }
            }
            catch (Exception ep)
            {
                MessageBox.Show("Error when playing file:(" + fn + ")\r\n" + ep.ToString());
            }
        }

        private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            playRow(e.RowIndex);
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            playRow(e.RowIndex);
        }



    }
}