using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class app_i18n_resx2json : System.Web.UI.Page
{
    [Serializable]
    public class jedOBJ
    {
        public Dictionary<string, Object> messages;

        public jedOBJ()
        {
            messages = new Dictionary<string, Object>();
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

        string siteLang = "EN";
        HttpCookie lang = Request.Cookies["siteLanguage"];
        siteLang = (lang != null) ? lang.Value : siteLang;

        string callback = (Request.QueryString["callback"] != null) ? Request.QueryString["callback"] : "";
        string path = Request.QueryString["path"];
        string customPath = (Request.QueryString["customPath"] != null) ? Request.QueryString["customPath"] : "";
        bool appendASPXExtension = (Request.QueryString["appendASPXExt"] != null) ? Convert.ToBoolean(Request.QueryString["appendASPXExt"]) : true; 

        string[] pathsArr = path.Split('/');

        string pathToResxFile = "";
        if (customPath == "")
            pathToResxFile = "/app/templates/" + pathsArr[0] + "/app_localresources/" + pathsArr[1] + ((appendASPXExtension) ? ".aspx" : "");
        else
            pathToResxFile = customPath + "/app_localresources/" + pathsArr[0] + ((appendASPXExtension) ? ".aspx" : "");

        jedOBJ jd = new jedOBJ();
        jd.messages.Add("", new Dictionary<string, string>(){
            {"domain", "messages"} , { "lang", "en" } , { "plural_forms" , "nplurals=2; plural=(n != 1);" }
        }); 

        //string keys = "";

        JavaScriptSerializer jss = new JavaScriptSerializer();

        System.Resources.ResXResourceReader rsxr = new System.Resources.ResXResourceReader(AppDomain.CurrentDomain.BaseDirectory + pathToResxFile + ((siteLang == "EN") ? "" : "." + siteLang) + ".resx");
        System.Collections.IDictionaryEnumerator dict = null; 

        bool fileExists = false;
        try
        {
            dict = rsxr.GetEnumerator();
            fileExists = true; 
        }
        catch (Exception ex)
        {
            //file not found fallback to default language.
            try
            {
                rsxr = new System.Resources.ResXResourceReader(AppDomain.CurrentDomain.BaseDirectory + pathToResxFile + ".resx");
                dict = rsxr.GetEnumerator();
                fileExists = true;
            }
            catch (Exception ex2)
            {
                fileExists = false;
            }
        }

        if (fileExists)
        {

            Dictionary<String, String> singulars = new Dictionary<String, String>();
            Dictionary<String, String> plurals = new Dictionary<String, String>();

            //moving to 2 dictionaries.
            while (dict.MoveNext())
            {   
                
                if (dict.Key.ToString().IndexOf("_plural_") == -1)
                {
                    //is singular
                    singulars.Add(dict.Key.ToString(), dict.Value.ToString());
                }
                else
                {
                    //is plural
                    plurals.Add(dict.Key.ToString().Replace("_plural_", ""), dict.Value.ToString());
                }
            }

            foreach (KeyValuePair<String, String> entry in singulars)
            {
                if (!plurals.ContainsKey(entry.Key)){
                    jd.messages.Add(entry.Key, new List<string>() { null, entry.Value });
                }else{
                    jd.messages.Add(entry.Key, new List<string>() { null, entry.Value, plurals[entry.Key] });
                }
            }

        }

        //jedJSON += keys + " } } "; 

        //Close the reader. '
        rsxr.Close();

        string jedJSON = ""; 
        //JSONP awful workaround. Should be a service that returns JSONP.
        if (callback != "") jedJSON = callback + "(" + jss.Serialize(jd) + ");";
        else jedJSON = jss.Serialize(jd); 

        Response.Write(jedJSON); 

    }
}