using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using TCX.Configuration;
using System.IO;

public partial class DrHandler : System.Web.UI.Page
{
    // /dr.aspx?dr=800
    protected void Page_Load(object sender, EventArgs e)
    {
        String dr = Request.Params.Get("dr");
        if (dr == null)
        {
            ErrorAnswer("Invalid parameter");
            return;
        }

        DN drDn = PhoneSystem.Root.GetDNByNumber(dr);
        if (drDn == null || !(drDn is IVR))
        {
            ErrorAnswer("Is not DR");
            return;
        }
        XmlDocument doc = new XmlDocument();
        doc.Load(Request.PhysicalApplicationPath+"DRbase.vxml");
        {
             XmlNode myDN = doc.SelectSingleNode("/vxml/var[@name='mydn']");
             Utils.AddAttr(myDN, "expr", "'"+dr+"'");
        }

        IVR ivr = drDn as IVR;
        int time = ivr.Timeout;

        string dnLength = PhoneSystem.Root.GetParameterByName("ENL").Value;

        XmlNode dn_len = doc.SelectSingleNode("/vxml/var[@name='dn_len']");
        Utils.AddAttr(dn_len, "expr", dnLength);

       	Parameter use_bk_music = PhoneSystem.Root.GetParameterByName("IVR_USEBK_MUSIC");
        if(use_bk_music!=null&&use_bk_music.Value=="1")
        {
            Parameter bk_music = PhoneSystem.Root.GetParameterByName("IVR_MOH_SOURCE");
            if(bk_music!=null&&bk_music.Value!="")
            {
                XmlNode bkMusicNode = doc.SelectSingleNode("/vxml/var[@name='bk_music']");
                Utils.AddAttr(bkMusicNode, "expr", ("'"+bk_music.Value+"'").Replace("\\", "/"));
            }
        }
        
        XmlNode form = doc.SelectSingleNode("/vxml/form[@id='name_here']");
        Utils.AddAttr(form, "id", ivr.Name);

        string grammar = "";
        foreach (IVRForward fwd in ivr.Forwards)
        {
            grammar += fwd.Number + "|";
            XmlNode block = 
                doc.SelectSingleNode("/vxml/form/block[@name='Action_" + fwd.Number + "']");
            IVRForwardType fwdt = (IVRForwardType)fwd.ForwardType;
            string fwd_dn = fwd.ForwardDN == null ? "endcall" : fwd.ForwardDN.Number;
            if (fwd.ForwardDN != null && (fwd.ForwardDN is IVR) && (fwd.ForwardDN as IVR).UseMSExchange)
                fwdt = IVRForwardType.Extension;
            EditActionBlock(fwd_dn, fwdt, block);
        }
        grammar += "[0-9]{" + dnLength + "}";

        XmlNode tout_block = doc.SelectSingleNode("/vxml/form/block[@name='timed_out']");

        bool asExtension = (ivr.TimeoutForwardDN != null && (ivr.TimeoutForwardDN is IVR) && (ivr.TimeoutForwardDN as IVR).UseMSExchange);

        EditActionBlock(
            ivr.TimeoutForwardDN == null ? "EndCall" : ivr.TimeoutForwardDN.Number,
            asExtension ? IVRForwardType.Extension : ivr.TimeoutForwardType,
            tout_block);

        XmlNode grm = doc.SelectSingleNode("/vxml/form/field/grammar");
        grm.InnerText = grammar;

        XmlNode prompt = grm.NextSibling;
        prompt.Attributes["timeout"].Value = ivr.Timeout.ToString()+"s";

        XmlNode audio = doc.CreateElement("audio");
        prompt.AppendChild(audio);
        String pathoffile;
        Parameter path = PhoneSystem.Root.GetParameterByName("IVRPROMPTPATH");
        if (path != null)
        {
            pathoffile = path.Value;
        }
        else
        {
            pathoffile = "C:/Program Files/3CX PhoneSystem/Bin/Interface";
        }
        XmlNode vad = doc.SelectSingleNode("/vxml/form/subdialog[@name='VAD_LINK']");
        DNProperty ext_link = drDn.GetPropertyByName("ExternalLink");
        if (ext_link != null) //if (ivr.PromptFilename.Contains("3CX VAD"))
        {
            Utils.AddAttr(vad, "cond", "1");
            Utils.AddAttr(audio, "src", Utils.GetPrompt("EMPTY"));
            
            String link = "'" + ext_link.Value + "?dr=" + drDn.Number + "'";
            Utils.AddAttr(vad, "srcexpr", link);
        }
        else
        {
            Utils.AddAttr(vad, "cond", "0");
            Utils.AddAttr(audio, "src", System.IO.Path.Combine(pathoffile, ivr.PromptFilename));
        }

        doc.Save(Response.OutputStream);
    }

    void ErrorAnswer(string err_msg)
    {
    }

    void EditActionBlock(string dn,IVRForwardType fwdt, XmlNode block)
    {
        XmlDocument doc = block.OwnerDocument;
        if (( dn == "endcall") &&
            ((fwdt != IVRForwardType.CallByName) && (fwdt != IVRForwardType.RepeatPrompt))) 
            fwdt = IVRForwardType.EndCall;

        if (fwdt.CompareTo(IVRForwardType.EndCall) == 0)
        {
            XmlNode exit = doc.CreateElement("goto");
            block.AppendChild(exit);
            Utils.AddAttr(exit, "nextitem", "blkExit");
            return;
        }
        if (fwdt.CompareTo(IVRForwardType.VoiceMail) == 0)
        {
            XmlNode assDn = doc.CreateElement("assign");
            block.AppendChild(assDn);
            Utils.AddAttr(assDn, "name", "dn_fwd");
            Utils.AddAttr(assDn, "expr", dn);
            XmlNode gotoN = doc.CreateElement("goto");
            block.AppendChild(gotoN);
            Utils.AddAttr(gotoN, "nextitem", "transfToVM");
            return;
        }
        if(fwdt.CompareTo(IVRForwardType.IVR) == 0)
        {
            XmlNode assDn = doc.CreateElement("assign");
            block.AppendChild(assDn);
            Utils.AddAttr(assDn, "name", "dn_fwd");
            Utils.AddAttr(assDn, "expr", dn);
            XmlNode gotoN = doc.CreateElement("goto");
            block.AppendChild(gotoN);
            Utils.AddAttr(gotoN, "nextitem", "transfToIVR");
            return;
        }
        if (fwdt.CompareTo(IVRForwardType.Extension) == 0 ||
            fwdt.CompareTo(IVRForwardType.RingGroup) == 0 ||
            fwdt.CompareTo(IVRForwardType.Queue) == 0)
        {
            XmlNode assDn = doc.CreateElement("assign");
            block.AppendChild(assDn);
            Utils.AddAttr(assDn, "name", "dn_fwd");
            Utils.AddAttr(assDn, "expr", dn);
            XmlNode gotoN = doc.CreateElement("goto");
            block.AppendChild(gotoN);
            Utils.AddAttr(gotoN, "nextitem", "transfToDN");
            return;
        }
        if (fwdt.CompareTo(IVRForwardType.CallByName) == 0)
        {
            XmlNode gotoN = doc.CreateElement("submit");
            block.AppendChild(gotoN);
            Utils.AddAttr(gotoN, "next", "#frmCBN");
            return;
        }

        XmlNode rept = doc.CreateElement("goto");
        block.AppendChild(rept);
        Utils.AddAttr(rept, "nextitem", "repeat");
    }
}
