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

namespace VR2WinApp
{
    public partial class QuickSearch : Form
    {
        public VR2.DBServerSetting db_set;
        public string sCaller;
        public string sCallee;
        public DateTime dtBegin;
        public DateTime dtEnd;
        public int RowIndexSelected;
        public EmailServerSetting email_set;
        //public string[] emails;

        public QuickSearch()
        {
            InitializeComponent();

            RowIndexSelected = -1;

            email_set = new EmailServerSetting();
            //emails = null;
        }

        public static bool GetBooleanFromXMLNode(XmlNode tmpNode)
        {
            if (tmpNode != null)
            {
                if (tmpNode.InnerText.Trim().ToUpper() == "TRUE")
                    return true;
                else
                {
                    if (tmpNode.InnerText.Trim() == "1")
                        return true;
                    else
                        return false;
                }
            }

            return false;
        }

        public bool LoadEmailNetConfigFromXML(string xmlFileName)
        {

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

            XmlElement root = xmlDoc.DocumentElement;
            XmlNode tmpNode = null;
            try
            {
                /*
                tmpNode = root.SelectSingleNode("//VoiceRecorder/NotifyEmails");
                if (tmpNode != null)
                {
                    try
                    {
                        string sEmails = tmpNode.InnerText.Trim();
                        if (sEmails.Length > 0)
                        {
                            char[] delimiters = new char[] { ';', ',' };
                            emails = sEmails.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
                        }
                    }
                    catch (Exception ex)
                    {
                        VRAPIASM.VRAPIEnv.Log(1, ex.ToString());
                    }
                }*/

                tmpNode = root.SelectSingleNode("//VoiceRecorder/SMTPServer/Server");
                if (tmpNode != null)
                    email_set.emailServer = tmpNode.InnerText;

                tmpNode = root.SelectSingleNode("//VoiceRecorder/SMTPServer/Port");
                if (tmpNode != null)
                    email_set.emailPort = Convert.ToUInt16(tmpNode.InnerText);

                tmpNode = root.SelectSingleNode("//VoiceRecorder/SMTPServer/EmailAddr");
                if (tmpNode != null)
                    email_set.emailAddr = tmpNode.InnerText;

                tmpNode = root.SelectSingleNode("//VoiceRecorder/SMTPServer/Password");
                if (tmpNode != null)
                    email_set.emailPassword = tmpNode.InnerText;

                email_set.emailSSL = GetBooleanFromXMLNode(root.SelectSingleNode("//VoiceRecorder/SMTPServer/SSL"));

            }
            catch (Exception ex)
            {
                VRAPIASM.VRAPIEnv.Log(1, ex.ToString());
            }

            return true;
        }


        private void QuickSearch_Load(object sender, EventArgs e)
        {
            DateTime dtNow = DateTime.Now;
            dtPicker1.Value = dtNow.AddDays(-5);

            dtNow = DateTime.Now;
            dtPicker2.Value = dtNow.AddDays(1);

            ContextMenu m = new ContextMenu();
            m.MenuItems.Add(new MenuItem("Play", new EventHandler(dataGridView1_PlayAudio)));
            m.MenuItems.Add(new MenuItem("Open Folder", new EventHandler(dataGridView1_OpenFolder)));
            m.MenuItems.Add(new MenuItem("Email Recording", new EventHandler(dataGridView1_EmailRecording)));
            m.MenuItems.Add(new MenuItem("Copy Audio File", new EventHandler(dataGridView1_CopyAudioFile)));


            //int currentMouseOverRow = dataGridView1.HitTest(e.X, e.Y).RowIndex;



            //m.Show(dataGridView1, new Point(e.Location.X, e.Location.Y));
            //m.Show(dataGridView1.PointToScreen(e.Location));

            ContextMenu = m;

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

        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            sCaller = tbCaller.Text;
            sCallee = tbCallee.Text;

            SearchData(sCaller, sCallee, dtPicker1.Value, dtPicker2.Value);
        }

        public void SearchData(string caller, string callee, DateTime dt1, DateTime dt2)
        {
            string commandStr = "SELECT CallerID, CalleeID, TimeInit, TimeBegin, TimeEnd, Duration, RecordPath, UniqueID FROM " + db_set.CallLogTableName + " WHERE ";

            bool cnd = false;

            if (dtPicker1.Checked)
            {
                if (cnd) commandStr += "AND ";
                commandStr += "TimeInit >= " + DateTimeToStr(dt1) + " ";
                cnd = true;
            }
            if (dtPicker2.Checked)
            {
                if (cnd) commandStr += "AND ";
                commandStr += "TimeInit <= " + DateTimeToStr(dt2) + " ";
                cnd = true;
            }

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

            if (callee.Length > 0)
            {
                if (cnd) commandStr += "AND ";
                commandStr += "CalleeID LIKE '%" + callee + "%' ";
                cnd = true;
            }
            if (!cnd)
            {
                commandStr = commandStr.Substring(0, commandStr.Length - 6); //remove WHERE
            }

            try
            {

                if (db_set.ConnectDB())
                {
                    string strCon = db_set.GetConnStr();
                    string strSQL = commandStr;
                    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";

                    dataGridView1.Columns["CallerID"].Width = 80;
                    dataGridView1.Columns["CalleeID"].Width = 80;
                    dataGridView1.Columns["TimeInit"].Width = 120;
                    dataGridView1.Columns["TimeBegin"].Width = 120;
                    dataGridView1.Columns["TimeEnd"].Width = 120;

                    dataGridView1.Columns["Duration"].Width = 50;
                    dataGridView1.Columns["RecordPath"].Width = 300;

                    dataGridView1.Columns["UniqueID"].Width = 160;


                    db_set.DisconnectDB();


                    SetStasticData();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                MessageBox.Show(commandStr);
            }

            /*
            if(dataGridView1.Rows.Count > 0)
            {
                string sValue = "";
                //dataGridView1.Rows[0].Cells[5].OwningColumn.CellType = sValue.GetType();
                dataGridView1.Rows[0].Cells[5].OwningColumn.ValueType = sValue.GetType();
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    try
                    {
                        sValue = dataGridView1.Rows[i].Cells[5].Value.ToString();
                        int sec = Convert.ToInt32(sValue);
                        int hour = sec / 3600;
                        sec -= hour * 3600;
                        int minute = sec / 60;
                        sec -= minute * 60;
                        sValue = string.Format("{0,2:D}", hour) + ":" + string.Format("{0,2:D}", minute) + ":" + string.Format("{0,2:D}", sec);
                        dataGridView1.Rows[i].Cells[5].ValueType = sValue.GetType();
                        dataGridView1.Rows[i].Cells[5].Value = sValue;
                    }
                    catch (Exception ex)
                    {
                        //MessageBox.Show(ex.ToString());
                    }
                }

                dataGridView1.Refresh();
            }
            */

        }

        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 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;
        }

        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[6].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 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);
        }

        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.");
            }
        }

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

        bool DeleteRecord(string rid, string fn)
        {
            if (rid == "" && fn == "") return false;

            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;
            }

        }

        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[7].Value.ToString();
                        string fn = dataGridView1.Rows[idx].Cells[6].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-1; i++)
                    {
                        try
                        {
                            string rid = dataGridView1.Rows[i].Cells[7].Value.ToString();
                            string fn = dataGridView1.Rows[i].Cells[6].Value.ToString();
                            DeleteRecord(rid, fn);
                        }
                        catch (Exception)
                        {
                            //MessageBox.Show(ex.ToString());
                        }
                    }
                    db_set.DisconnectDB();
                    RefreshDataGridView();
                }
                else
                {
                    MessageBox.Show("Cannot connect to database!", "Error");
                }
            }
        }

        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[5].Value == null) continue;

                string dur = dataGridView1.Rows[i].Cells[5].Value.ToString();
                string fn = dataGridView1.Rows[i].Cells[6].Value.ToString();
                string rid = dataGridView1.Rows[i].Cells[7].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 dataGridView1_PlayAudio(object sender, EventArgs e)
        {
            if (RowIndexSelected < 0)
            {
                MessageBox.Show("Wrong row to operate on");
                return;
            }

            playRow(RowIndexSelected);
        }

        private void dataGridView1_OpenFolder(object sender, EventArgs e)
        {
            if (RowIndexSelected < 0)
            {
                MessageBox.Show("Wrong row to operate on");
                return;
            }

            string fn = dataGridView1.Rows[RowIndexSelected].Cells[6].Value.ToString();

            if (fn.Length > 0)
            {
                try
                {
                    FileInfo fi = new FileInfo(fn);

                    if (!System.IO.Directory.Exists(fi.DirectoryName))
                    {
                        MessageBox.Show(fi.DirectoryName + " doesn't exist, so it can't be openned");
                    }
                    else
                    {
                        Process.Start(fi.DirectoryName);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }



        }

       private void dataGridView1_CopyAudioFile(object sender, EventArgs e)
        {
            if (RowIndexSelected < 0)
            {
                MessageBox.Show("Wrong row to operate on. Please select a row.");
                return;
            }

            string WavFile = dataGridView1.Rows[RowIndexSelected].Cells[6].Value.ToString();

            StringCollection paths = new StringCollection();
            paths.Add(WavFile);
            Clipboard.SetFileDropList(paths);
        }

        private void dataGridView1_EmailRecording(object sender, EventArgs e)
        {
            btnEmailRecording_Click(sender, e);

            /*
            if (RowIndexSelected < 0)
            {
                MessageBox.Show("Wrong row to operate on");
                return;
            }

            if (email_set.emailAddr.Length > 0 && email_set.emailServer.Length > 0)
            {
                try
                {
                    string CallerId = dataGridView1.Rows[RowIndexSelected].Cells[0].Value.ToString();
                    string CalleeId = dataGridView1.Rows[RowIndexSelected].Cells[1].Value.ToString();
                    string TimeInit = dataGridView1.Rows[RowIndexSelected].Cells[2].Value.ToString();
                    string TimeBegin = dataGridView1.Rows[RowIndexSelected].Cells[3].Value.ToString();
                    string TimeEnd = dataGridView1.Rows[RowIndexSelected].Cells[4].Value.ToString();
                    string Duration = dataGridView1.Rows[RowIndexSelected].Cells[5].Value.ToString();
                    string WavFile = dataGridView1.Rows[RowIndexSelected].Cells[6].Value.ToString();

                    MailMessage myMail = new MailMessage(email_set.emailAddr, email_set.emailAddr);
                    myMail.Subject = "Recording log - " + TimeInit + " " + CallerId + " " + CalleeId;

                    myMail.Body = "Caller: " + CallerId + "\r\n";
                    myMail.Body += "Called: " + CalleeId + "\r\n";
                    myMail.Body += "Call Inited Time: " + TimeInit + "\r\n";
                    myMail.Body += "Call Begin Time: " + TimeBegin + "\r\n";
                    myMail.Body += "Call End Time: " + TimeEnd + "\r\n";
                    myMail.Body += "Call Duration: " + Duration + " seconds\r\n";

                    Attachment item = new Attachment(WavFile);
                    myMail.Attachments.Add(item);

                    if (emails != null)
                    {
                        if (emails.Length > 0)
                        {
                            myMail.To.Clear();
                            for (int i = 0; i < emails.Length; i++)
                            {
                                MailAddress to = new MailAddress(emails[i]);
                                myMail.To.Add(to);
                            }
                        }
                    }

                    SmtpClient smtp_client = new SmtpClient(email_set.emailServer, email_set.emailPort);

                    smtp_client.UseDefaultCredentials = false;
                    smtp_client.Credentials = new NetworkCredential(email_set.emailAddr, email_set.emailPassword);
                    smtp_client.EnableSsl = email_set.emailSSL;

                    // Set the method that is called back when the send operation ends.
                    //smtp_client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);

                    //string userState = "test message1";
                    //smtp_client.SendAsync(myMail, this);


                    smtp_client.Send(myMail);

                    MessageBox.Show("Email was sent successfully!");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                    VRAPIASM.VRAPIEnv.Log(1, ex.Message);
                }

                //VRAPIASM.VRAPIEnv.Log(4, "VR2Main timerTick() error event ends!");

            }
            else
            {
                MessageBox.Show("Email server config is not complete");
            }*/

        }

        /*
        private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            RowIndexSelected = e.RowIndex;
            //playRow();

            if (e.Button == MouseButtons.Right)
            {
                //int currentMouseOverRow = dataGridView1.HitTest(e.X, e.Y).RowIndex;


            }

        }*/

        private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
        {
            //if (e.Button == MouseButtons.Right)
            {
                var hti = dataGridView1.HitTest(e.X, e.Y);
                dataGridView1.ClearSelection();
                if (hti.RowIndex >= 0 && hti.RowIndex < dataGridView1.Rows.Count - 1)
                {
                    dataGridView1.Rows[hti.RowIndex].Selected = true;
                    RowIndexSelected = hti.RowIndex;
                }
                else
                {
                    RowIndexSelected = -1;
                }
            }
        }

        private void btnEmailRecording_Click(object sender, EventArgs e)
        {
            if (RowIndexSelected < 0)
            {
                MessageBox.Show("Wrong row to operate on. Please select a row.");
                return;
            }


            if (email_set.emailAddr.Length > 0 && email_set.emailServer.Length > 0)
            {
            }
            else
            {
                MessageBox.Show("Email server config is not complete");
                return;
            }

            EmailRecording dlg = new EmailRecording();

            dlg.CallerId = dataGridView1.Rows[RowIndexSelected].Cells[0].Value.ToString();
            dlg.CalleeId = dataGridView1.Rows[RowIndexSelected].Cells[1].Value.ToString();
            dlg.TimeInit = dataGridView1.Rows[RowIndexSelected].Cells[2].Value.ToString();
            dlg.TimeBegin = dataGridView1.Rows[RowIndexSelected].Cells[3].Value.ToString();
            dlg.TimeEnd = dataGridView1.Rows[RowIndexSelected].Cells[4].Value.ToString();
            dlg.Duration = dataGridView1.Rows[RowIndexSelected].Cells[5].Value.ToString();
            dlg.WavFile = dataGridView1.Rows[RowIndexSelected].Cells[6].Value.ToString();

            dlg.email_set = email_set;

            dlg.ShowDialog();
        }

        private void btnCopyToClipboard_Click(object sender, EventArgs e)
        {
            dataGridView1_CopyAudioFile(sender, e);
        }

    }
}