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 System.Net.Mail;
using System.Net.Mime;
using VR2;
using System.Collections.Specialized;

namespace VR2WinApp
{
    public partial class ImportFolder : Form
    {
        public VR2.DBServerSetting db_set;

        public ImportFolder()
        {
            InitializeComponent();
        }

        public int ImportXMLFileToDB(string xmlfile)
        {
            string call_id = "";
            string sip_id = "";
            bool succ = true;
            string caller_ip = "";
            string caller_name = "";
            string caller_audio = "";
            string callee_ip = "";
            string callee_name = "";
            string callee_audio = "";
            string time_init = "";
            string time_begin = "";
            string time_end = "";
            string time_dur = "";
            string record_path = "";
            string dtmf = "";
            string record_filenum = "";

            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(xmlfile);
            }
            catch (Exception)
            {
                return 0;
            }

            XmlElement root = xmlDoc.DocumentElement;
            XmlNode tmpNode = null;
            try
            {
                tmpNode = root.SelectSingleNode("//CALL/ID");
                if (tmpNode != null)
                    call_id = tmpNode.InnerText;
                else
                    return 0;

                tmpNode = root.SelectSingleNode("//CALL/SIP-ID");
                if (tmpNode != null)
                    sip_id = tmpNode.InnerText;
                else
                    return 0;

                tmpNode = root.SelectSingleNode("//CALL/SUCCEED");
                if (tmpNode != null)
                    succ = tmpNode.InnerText.ToLower() == "true";
                else
                    return 0;

                tmpNode = root.SelectSingleNode("//CALL/CALLER/IPADDR");
                if (tmpNode != null)
                    caller_ip = tmpNode.InnerText;
                else
                    return 0;

                tmpNode = root.SelectSingleNode("//CALL/CALLER/NAME");
                if (tmpNode != null)
                    caller_name = tmpNode.InnerText;
                else
                    return 0;

                tmpNode = root.SelectSingleNode("//CALL/CALLER/AUDIO");
                if (tmpNode != null)
                    caller_audio = tmpNode.InnerText;
                else
                    return 0;

                tmpNode = root.SelectSingleNode("//CALL/CALLEE/IPADDR");
                if (tmpNode != null)
                    callee_ip = tmpNode.InnerText;
                else
                    return 0;

                tmpNode = root.SelectSingleNode("//CALL/CALLEE/NAME");
                if (tmpNode != null)
                    callee_name = tmpNode.InnerText;
                else
                    return 0;

                tmpNode = root.SelectSingleNode("//CALL/CALLEE/AUDIO");
                if (tmpNode != null)
                    callee_audio = tmpNode.InnerText;
                else
                    return 0;

                tmpNode = root.SelectSingleNode("//CALL/TIME/INIT");
                if (tmpNode != null)
                    time_init = tmpNode.InnerText;
                else
                    return 0;

                tmpNode = root.SelectSingleNode("//CALL/TIME/BEGIN");
                if (tmpNode != null)
                    time_begin = tmpNode.InnerText;
                else
                    return 0;

                tmpNode = root.SelectSingleNode("//CALL/TIME/END");
                if (tmpNode != null)
                    time_end = tmpNode.InnerText;
                else
                    return 0;

                tmpNode = root.SelectSingleNode("//CALL/TIME/DURATION");
                if (tmpNode != null)
                    time_dur = tmpNode.InnerText;
                else
                    return 0;

                tmpNode = root.SelectSingleNode("//CALL/RECORD/PATH");
                if (tmpNode != null)
                    record_path = tmpNode.InnerText;
                else
                    return 0;

                tmpNode = root.SelectSingleNode("//CALL/RECORD/FILENUM");
                if (tmpNode != null)
                    record_filenum = tmpNode.InnerText;;

                tmpNode = root.SelectSingleNode("//CALL/DTMF");
                if (tmpNode != null)
                    dtmf = tmpNode.InnerText;

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

            SqlCommand myComm = null;

            string commandStr = "SELECT * FROM calls where UniqueID = '" + call_id + "'";

            try
            {
                myComm = new SqlCommand(commandStr, db_set.myConn);
                myComm.CommandTimeout = 3;
                SqlDataReader myReader = myComm.ExecuteReader();

                if (myReader.HasRows)
                {
                    myReader.Close();
                }
                else
                {
                    myReader.Close();

                    //VRAPIASM.VRAPIEnv.Log(4, "Inserting DB record");

                    //Second Step INSERT
                    commandStr = "INSERT INTO calls(ChanID, Succeed, CallerIP, CallerID, CallerName, CalleeIP, CalleeID, CalleeName, TimeInit, TimeBegin, TimeEnd, Duration, UniqueID, RecordPath, RecordFileNum, DIR, DTMF, VRType, ChanName) VALUES(";

                    int chanid = 1;
                    commandStr += chanid.ToString() + ", ";

                    if (succ)
                        commandStr += "1, ";
                    else
                        commandStr += "0, ";

                    commandStr += "'" + caller_ip + "', ";
                    commandStr += "'" + GetAddrID(caller_name) + "', ";
                    commandStr += "'', ";

                    commandStr += "'" + callee_ip + "', ";
                    commandStr += "'" + GetAddrID(callee_name) + "', ";
                    commandStr += "'', ";

                    commandStr += "'" + time_init + "', ";
                    if (succ)
                        commandStr += "'" + time_begin + "', ";
                    else
                        commandStr += "NULL, ";

                    commandStr += "'" + time_end + "', ";

                    if (succ)
                    {
                        commandStr += time_dur + ", ";
                    }
                    else
                        commandStr += "0, ";

                    commandStr += "'" + call_id + "', ";

                    if (succ)
                    {
                        commandStr += "'" + record_path + "', ";
                        commandStr += record_filenum + ", ";
                    }
                    else
                    {
                        commandStr += "'', ";
                        commandStr += "0, ";
                    }

                    commandStr += "0, ";
                    commandStr += "'" + dtmf + "', 0, '')";

                    myComm.CommandText = commandStr;
                    if (myComm.ExecuteNonQuery() == 1)
                    {
                        return 1;
                    }
                    else
                    {
                        return 0;
                    }

                }
            }
            catch (Exception ex)
            {
                //VRAPIASM.VRAPIEnv.Log(1, "SQL:" + commandStr);
                //VRAPIASM.VRAPIEnv.Log(1, e.ToString());
                //db_set.DisconnectDB();
                return 0;
            }

            return 0;

        }

        public static string GetSIPAddressInfo(int flag, string sipAddr)
        {
            if (sipAddr == null)
                return "";

            if (sipAddr.Length == 0)
                return "";

            //a fix for google andriod phone bad implementation
            if (sipAddr.IndexOf("<sip:") == -1 && sipAddr.IndexOf("sip:") >= 0)
            {
                int idx1 = sipAddr.IndexOf("sip:");
                if (idx1 == 0)
                {
                    sipAddr = "<" + sipAddr + ">";
                }
                else
                {
                    sipAddr = sipAddr.Substring(0, idx1) + "<" + sipAddr.Substring(idx1) + ">";
                }
            }

            int nPos = 0;
            int nPos1 = 0;

            if (flag == 0) //display name
            {
                nPos = sipAddr.IndexOf("<sip:");
                if (nPos == -1 || nPos == 0)
                    return "";
                else
                    return sipAddr.Substring(0, nPos);
            }
            else if (flag == 1) //user name
            {
                nPos = sipAddr.IndexOf("<sip:");
                if (nPos == -1)
                    return "";
                else
                {
                    nPos += 5;

                    nPos1 = sipAddr.IndexOf('@', nPos);
                    if (nPos1 == -1)
                        return "";
                    else
                        return sipAddr.Substring(nPos, nPos1 - nPos);
                }
            }
            else if (flag == 2) //ip address
            {
                nPos = sipAddr.IndexOf('@');
                if (nPos == -1)
                {
                    nPos = sipAddr.IndexOf("<sip:");
                    if (nPos == -1)
                        return "";
                    else
                        nPos += 5;
                }
                else
                    nPos += 1;

                nPos1 = sipAddr.IndexOf('>', nPos);

                string ipAddr = "";

                if (nPos1 == -1)
                    ipAddr = sipAddr.Substring(nPos);
                else
                    ipAddr = sipAddr.Substring(nPos, nPos1 - nPos);

                nPos = ipAddr.IndexOf(';');
                if (nPos != -1)
                    ipAddr = ipAddr.Substring(0, nPos);

                nPos = ipAddr.IndexOf(':');
                if (nPos != -1)
                    ipAddr = ipAddr.Substring(0, nPos);

                return ipAddr;
            }
            else if (flag == 3) //port
            {
                nPos = sipAddr.IndexOf('@');
                if (nPos == -1)
                {
                    nPos = sipAddr.IndexOf("<sip:");
                    if (nPos == -1)
                        return "";
                    else
                        nPos += 5;
                }
                else
                    nPos += 1;

                nPos1 = sipAddr.IndexOf('>', nPos);

                string ipAddr = "";

                if (nPos1 == -1)
                    ipAddr = sipAddr.Substring(nPos);
                else
                    ipAddr = sipAddr.Substring(nPos, nPos1 - nPos);

                nPos = ipAddr.IndexOf(';');
                if (nPos != -1)
                    ipAddr = ipAddr.Substring(0, nPos);

                nPos = ipAddr.IndexOf(':');
                if (nPos == -1)
                    ipAddr = "";
                else
                    ipAddr = ipAddr.Substring(nPos + 1);

                return ipAddr;
            }

            return "";
        }

        public string GetAddrID(string s)
        {
            string ret = "";

            try
            {
                if (s.Contains("sip:"))
                {
                    string sDisplayName = GetSIPAddressInfo(0, s);
                    string sUserName = GetSIPAddressInfo(1, s);

                    char[] trimChars = { '-', ' ', '\'', '"' };
                    sDisplayName = sDisplayName.Trim(trimChars);
                    sUserName = sUserName.Trim(trimChars);

                    sDisplayName = sDisplayName.Replace('\'', ' ');
                    sUserName = sUserName.Replace('\'', ' ');

                    sDisplayName = sDisplayName.Trim();
                    sUserName = sUserName.Trim();

                    if (sDisplayName.Length > 0)
                        ret = sDisplayName + "-" + sUserName;
                    else
                        ret = sUserName;
                }
            }
            catch (Exception ex)
            {
                //VRAPIASM.VRAPIEnv.Log(1, "Get ID Error From String: " + s);
                //VRAPIASM.VRAPIEnv.Log(1, ex.ToString());
                ret = s;
            }

            if (ret.Length > 80)
                ret = ret.Substring(0, 80);

            return ret;
        }


        public void GetFilesInSubDir(string dir, List<string> filenames, string ext)
        {
            DirectoryInfo d = new DirectoryInfo(dir);
            FileInfo[] Files = d.GetFiles(ext);
            DirectoryInfo[] Dirs = d.GetDirectories();

            foreach (FileInfo file in Files)
            {
                filenames.Add(file.FullName);
            }

            foreach (DirectoryInfo d1 in Dirs)
            {
                GetFilesInSubDir(d1.FullName, filenames, ext);
            }
        }

        private void btnBrowser_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                tbFolder.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            List<string> fnames = new List<string>();
            GetFilesInSubDir(tbFolder.Text, fnames, "*.xml");
            int cnt = 0;
            foreach (string s in fnames)
            {
                cnt += ImportXMLFileToDB(s);
            }
            MessageBox.Show(cnt.ToString() + " records imported");
        }
    }
}
