using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;

class CbnUser
{
    static string[] digits = { "0", "1", "abc", "def", "ghi",
        "jkl", "mno", "pqrs", "tuv", "wxyz" };

    public string sSelfId;
    public string sDN;

    CbnUser(string sid,string sdn)
    {
        sSelfId = sid;
        sDN = sdn;
    }

    static public CbnUser[] Enlist(string mask)
    {
        Extension[] ext_list = PhoneSystem.Root.GetExtensions();
        string base_path = Utils.GetVoicemailPath();
        base_path = Path.GetFullPath(base_path + @".\Data\");

        ArrayList list = new ArrayList();
        foreach (Extension ext in ext_list)
        {
            if (!Matches(ext.LastName.ToLowerInvariant(), mask))
                continue;
            string sid = Path.Combine(base_path, ext.Number + "\\Self_id_prompt.wav");
            if (File.Exists(sid))
            {
                list.Add( new CbnUser(sid, ext.Number) );
            }
        }

        CbnUser[] arr = new CbnUser[list.Count];
        list.CopyTo(arr);
        return arr;
    }

    private static bool Matches(string name, string mask)
    {
        if (mask.Length > name.Length)
            return false;

        char[] mch = mask.ToCharArray();
        char[] nch = name.ToCharArray();
        for (int i = 0; i < mch.Length; i++)
        {
            int idx = mch[i] - '0';
            if (digits[idx].IndexOf(nch[i]) == -1)
                return false;
        }
        return true;
    }
};

public partial class CBN : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        String input = Request.Params.Get("input");
        XmlDocument doc = new XmlDocument();

        //PhoneSystem.ApplicationName = "VxmlGen";
        //PhoneSystem.Root.GetTenants();

        if (input == null)
        {
            PrepareStartPage(doc);
        }
        else
            PrepareSecondPage(doc,input);

        Response.Expires = 0;
        Response.Cache.SetNoStore();
        Response.BufferOutput = true;
        Response.AddHeader("Connection", "close");

        doc.Save(Response.OutputStream);
    }

    private void PrepareStartPage(XmlDocument doc)
    {
        doc.Load(Request.PhysicalApplicationPath + "CallByName.vxml");

        string minInp = 
            PhoneSystem.Root.GetParameterByName("CALLBYNAME_MINLEN").Value;

        XmlNode grm = doc.SelectSingleNode("/vxml/form/field/grammar");
        grm.InnerText = "#|[0-9]{" + minInp + "}";
    }

    private void PrepareSecondPage(XmlDocument doc, string input)
    {
        doc.Load(Request.PhysicalApplicationPath + "CallByName2.vxml");

        XmlNode blkSel = doc.SelectSingleNode("/vxml/form/block[@name='blkSelect']");
        CbnUser[] list = CbnUser.Enlist(input);
        if (list.Length == 0)
        {
            blkSel.FirstChild.Attributes["next"].Value = "#frmNone";
            return;
        }

        if (list.Length == 1)
        {
            blkSel.FirstChild.Attributes["next"].Value = "#frmSingle";
            XmlNode vFwdDn = doc.SelectSingleNode("/vxml/var[@name='dn_fwd']");
            CbnUser usr = list.GetValue(0) as CbnUser;
            vFwdDn.Attributes["expr"].Value=usr.sDN;
            return;
        }

        if (list.Length < 10)
        {
            blkSel.FirstChild.Attributes["next"].Value = "#frmChoose";
            XmlNode fld = doc.SelectSingleNode("/vxml/form/field[@name='fldChoose']");
            XmlNode grm = fld.FirstChild;
            XmlNode prm = grm.NextSibling;
            XmlNode lastAudio = prm.LastChild;
            XmlNode filled = prm.NextSibling;
            XmlNode if2 = filled.SelectSingleNode("./if[2]");
            XmlNode prevIf = null;

            string sGrm = "";
            for (int i = 0; i < list.Length; i++)
            {
                sGrm += i.ToString() + "|";
                XmlNode audio = doc.CreateElement("audio");
                prm.InsertBefore(audio, lastAudio);
                // to call to...
                Utils.AddAttr(audio, "src", "GetPrompt.aspx?id=TOCALL_TO");

                // <self id>
                audio = audio.Clone();
                prm.InsertBefore(audio, lastAudio);
                audio.Attributes["src"].Value = list[i].sSelfId;//encode?

                // "press..."
                audio = audio.Clone();
                prm.InsertBefore(audio, lastAudio);
                audio.Attributes["src"].Value = "GetPrompt.aspx?id=PRESS";

                // <dtmf>
                audio = audio.Clone();
                prm.InsertBefore(audio, lastAudio);
                audio.Attributes["src"].Value = "GetPrompt.aspx?id=NUM_" + i.ToString();

                // pause
                audio = audio.Clone();
                prm.InsertBefore(audio, lastAudio);
                audio.Attributes["src"].Value = "GetPrompt.aspx?id=EMPTYMSG";

                if (prevIf != null)
                {
                    if2 = prevIf.Clone();
                    filled.InsertAfter(if2, prevIf);
                }

                if2.Attributes["cond"].Value = "fldChoose == '" + i.ToString() + "'";
                if2.FirstChild.Attributes["expr"].Value = list[i].sDN;

                prevIf = if2;
            }

            grm.InnerText = sGrm+"#";
        }
    }
}
