using System;
using System.Data;
using System.Configuration;
using System.Web;
//using System.Web.Security;
using System.Web.UI;
//using System.Web.UI.WebControls;
//using System.Web.UI.WebControls.WebParts;
//using System.Web.UI.HtmlControls;
using System.Xml;
using TCX.Configuration;
using System.IO;

public partial class _Default : System.Web.UI.Page 
{
    protected String UriParamChars(String inp)
    {
        String res = "";
        foreach (char c in inp)
        {
            if (c == '#')
                res += "%23";
            else if (c == '/')
                res += "%2F";
            else
                res += c;
        }
        return res;
    }

    protected String MakeParams(String dn, String to, String from, String menu,String isid)
    {
        String res = "";
        if (dn != null && dn.Length > 0)
        {
            res += "dn=" + dn;
        }
        if (to != null && to.Length > 0)
        {
            if (res.Length > 0) res += "&";
            res += "to=" + to;
        }
        if (from != null && from.Length > 0)
        {
            if (res.Length > 0) res += "&";
            res += "from=" + from;
        }
        if (menu != null && menu.Length > 0)
        {
            if (res.Length > 0) res += "&";
            res += "IVRHandlerMENU=" + menu;
        }
        if (isid != null && isid.Length > 0)
        {
            if (res.Length > 0) res += "&";
            res += "ISID=" + UriParamChars(isid);//Uri.EscapeUriString(isid);
        }
        return res;
    }

    protected String ParseForPrompt(String subj)
    {
        String result = "EMPTY";
        int pos_b = subj.IndexOf("p=");
        if (pos_b < 0)
            return result;
        pos_b += 2; // skip 'p=', point to the beginning of prompt name
        int pos_e = subj.IndexOf(';', pos_b);
        if (pos_e < 0)
            result = subj.Substring(pos_b);
        else
            result = subj.Substring(pos_b, pos_e - pos_b);
        return result;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        String from = Page.Request.Params.Get("IVRHandlerFROM");
        String DispName = Page.Request.Params.Get("FromDispName");
        String to = Page.Request.Params.Get("IVRHandlerTO");
        String menu = Page.Request.Params.Get("IVRHandlerMENU");
        String isid = Page.Request.Params.Get("ISID");
        String mtype = "invalid";
        String ec_prompt = "EMPTY";
        String dr_link = null;
        String CallerNameAudio = "";

        if (to == null)
            to = "unk";
        if (from == null)
            from = "unk";
        if (menu == null)
            menu = "unk";

        //try
        //{
        //    PhoneSystem.ApplicationName = "VxmlGen";
        //    PhoneSystem.Root.Connect();
        //}
        //catch(Exception)
        //{}

        UpdateRootVxml();

        DN to_dn = PhoneSystem.Root.GetDNByNumber(to);
        DN from_dn = PhoneSystem.Root.GetDNByNumber(from);
        if (menu == "MakeCall")
        {
            mtype = "make_call";
            if (to.ToLower()=="makecall")
                mtype = "end_call";
        }
        else if(menu=="PlayFile")
        {
             mtype="play_file";
             to_dn=null;
             from_dn=null;
        }
        else if(menu=="RecordFile")
        {
             to = HttpUtility.UrlEncode(to);
             mtype="rec_file";
             to_dn=null;
             from_dn=null;
        }
        else if (menu == "EndCall")
        {
            mtype = "end_call";
            ec_prompt = ParseForPrompt( Page.Request.Params.Get("IVRSubject") );
        }
        else if (to_dn != null)
        {
            if (to_dn is SpecialMenu&&to_dn.Number==menu)
                mtype = "vmail_menu";
            else if (to_dn is Queue&&to_dn.Number==menu)
                mtype = "queue_menu";
            else if (to_dn is IVR&&to_dn.Number==menu)
                mtype = "dr_menu";
            else if (menu == "RecordMessage")
                mtype = "rec_menu";
            else if (menu == "IVRForward")
            {
                mtype = "boom_caller";
                DNProperty screen = to_dn.GetPropertyByName("REBOUNDSCREENING");
                if (screen != null && (screen.Value.ToString() == "1"))
                    CallerNameAudio = Page.Request.Params.Get("IVRCallerNameAudio");
            }
            else if (menu == "IVRFwdAcceptor")
            {
                mtype = "boom_acceptor";
                CallerNameAudio = Page.Request.Params.Get("IVRCallerNameAudio");
            }
        }
        else
        {
            to_dn = PhoneSystem.Root.GetDNByNumber(menu);
            if (to_dn != null && to_dn is IVR)
                mtype = "dr_menu";
        }

        if (to_dn != null)
        {
            DNProperty ext_link = to_dn.GetPropertyByName("ExternalLink");
            if (ext_link != null)
            {
                dr_link = ext_link.Value;
            }
        }

        String fromt = "line";
        String ext_pin=null, ext_playcid=null, ext_playdt=null;


        if (from_dn != null)
        {
            if (from_dn is Extension)
            {
                //PIN is required by default
                bool required = true;
                {
                    DNProperty p = from_dn.GetPropertyByName("VOICEMAILPINAUTH");
                    if(p!=null) //if DNProperty is set then use its value
                    {
                        required = p.Value!="0";
                    }
                    else //otherwise - use value of the global parameter
                    {
                        Parameter par = PhoneSystem.Root.GetParameterByName("VMPINREQUIRED");
                        if(par!=null)
                        {
                            required = (par.Value!="0");
                        }
                    }
                }
                fromt = "ext";
                Extension from_ext = from_dn as Extension;
                if (from_ext.VMEnabled)
                {
                    if (required)
                        ext_pin = "askPinOnly";// from_ext.VMPIN;
                    else
                        ext_pin = "NOTREQUIRED";

                    ext_playcid = from_ext.VMPlayCallerID ? "1" : "0";
                    ext_playdt = ((int)from_ext.VMPlayMsgDateTime).ToString();
                }
            }
            else if (from_dn is IVR)
                fromt = "ivr";
        }

        String templ_name = Request.PhysicalApplicationPath+ "start.xml";

        XmlDocument doc = new XmlDocument();
        doc.Load(templ_name);

        XmlNodeList vars = doc.SelectNodes("/vxml/var");
        foreach (XmlNode v in vars)
        {
            if (v.Attributes["name"] == null)
                continue;

            switch (v.Attributes["name"].Value)
            {
                case "from":
                    v.Attributes["expr"].Value = "'" + from + "'";
                    break;
                case "from_cname":
                    if (DispName != null && DispName != "")
                    {
                        v.Attributes["expr"].Value = "'" + HttpUtility.HtmlEncode(HttpUtility.HtmlEncode(DispName)) + "'";
                    }
                    else
                    {
                        v.Attributes["expr"].Value = "''";
                    }
                    break;
                case "to":
                    v.Attributes["expr"].Value = "'" + to + "'";
                    break;
                case "menu":
                    v.Attributes["expr"].Value = "'" + menu + "'";
                    break;
                case "isid":
                    v.Attributes["expr"].Value = "'" + isid + "'";
                    break;
                case "ivr_menu_type":
                    v.Attributes["expr"].Value = "'" + mtype + "'";
                    break;
                case "from_type":
                    v.Attributes["expr"].Value = "'" + fromt + "'";
                    break;
                case "ec_prompt":
                    v.Attributes["expr"].Value = "'" + ec_prompt + "'";
                    break;
                case "caller_name_audio":
                    v.Attributes["expr"].Value = "'" + CallerNameAudio + "'";
                    break;
                case "dr_link":
                    if (dr_link != null)
                        v.Attributes["expr"].Value = "'" + dr_link + "'";
                    break;
            }
        }

        XmlNode ins = doc.SelectSingleNode("/vxml/form[@id='main']");
        if (ext_pin != null)
        {
            XmlNode var = doc.CreateElement("var");
            ins.ParentNode.InsertBefore(var, ins);
            Utils.AddAttr(var, "name", "ext_pin");
            Utils.AddAttr(var, "expr", "'" + ext_pin + "'");
        }
        else
        {
            XmlNode var = doc.CreateElement("var");
            ins.ParentNode.InsertBefore(var, ins);
            Utils.AddAttr(var, "name", "ext_pin");
            Utils.AddAttr(var, "expr", "''");
        }
        if (ext_playcid != null)
        {
            XmlNode var = doc.CreateElement("var");
            ins.ParentNode.InsertBefore(var, ins);
            Utils.AddAttr(var, "name", "ext_playcid");
            Utils.AddAttr(var, "expr", "'" + ext_playcid + "'");
        }

        if (ext_playdt != null)
        {
            XmlNode var = doc.CreateElement("var");
            ins.ParentNode.InsertBefore(var, ins);
            Utils.AddAttr(var, "name", "ext_playdt");
            Utils.AddAttr(var, "expr", "'" + ext_playdt + "'");
        }


        Response.BufferOutput = true;
        Response.Expires = 0;
        Response.Cache.SetNoStore();
        Response.Clear();

        doc.Save(Response.Output);
        Response.AddHeader("Connection", "close");
        Response.Flush();
        GC.Collect();
    }

    private void UpdateRootVxml()
    {
        try
        {
            int change = 0;
            XmlDocument root = new XmlDocument();
            string filename = Request.PhysicalApplicationPath + "root.vxml";
            root.Load(filename);
            XmlNode var = root.SelectSingleNode("/vxml/var[@name='rtOperator']");
            String rtOperator = "'" + PhoneSystem.Root.GetParameterByName("OPERATOR").Value + "'";
            if ((var != null) && (var.Attributes["expr"].Value != rtOperator))
            {
                change++;
                var.Attributes["expr"].Value = rtOperator;
            }
            var = root.SelectSingleNode("/vxml/var[@name='rtPbxSipPort']");
            String sipport = "':" + PhoneSystem.Root.GetParameterByName("SIPPORT").Value + "'";
            if ((var != null) && (var.Attributes["expr"].Value != sipport))
            {
                change++;
                var.Attributes["expr"].Value = sipport;
            }

            var = root.SelectSingleNode("/vxml/var[@name='rtMOH']");
            string path = PhoneSystem.Root.GetParameterByName("IVRPROMPTPATH").Value;
            string file = PhoneSystem.Root.GetParameterByName("MUSICONHOLDFILE").Value;
            string moh = "'" + Path.Combine(path, file) + "'";
            if ((var != null) && (var.Attributes["expr"].Value != moh))
            {
                change++;
                var.Attributes["expr"].Value = moh;
            }

            //update SIP port??
            if (change > 0)
            {
                try
                {
                    File.Delete(filename + ".bak");
                    File.Move(filename, filename + ".bak");
                }
                catch (Exception) { }
                root.Save(filename);
            }
        }
        catch (Exception) { }
    }
}
