using DotPrograms;
using System;
using System.Reflection;
using System.Web.Script.Serialization;
using System.Web.UI;
using Helpers.Log;
using log4net;

public partial class dotPrograms_dotProgramCompiler : Page
{
    private JavaScriptSerializer jss = new JavaScriptSerializer();
    private ILog logger = Logger.GetLogger(MethodBase.GetCurrentMethod().DeclaringType.Name);
        
    protected void Page_Load(object sender, EventArgs e)
    {
        Response response;

        try
        {
            string action = Request.Form["action"];

            if (action != null)
            {
                switch (action.ToString().ToUpper())
                {
                    case "COMPILE":
                        SourceCode src = jss.Deserialize<SourceCode>(Request.Form["sourceCode"]);

                        var compileResp = DotProgramCompiler.Compile(src);

                        response = new Response
                        {
                            Success = compileResp.Success,
                            Message = compileResp.Message,
                            Data = compileResp.Data,
                        };
                        break;
                    default:
                        response = new Response
                        {
                            Success = false,
                            Message = string.Format("Action '{0} is not supported'.", action),
                        };
                        break;
                }
            }
            else
            {
                response = new Response
                {
                    Success = false,
                    Message = "Parameter 'Action' can not be empty or null.",
                };
            }
        }
        catch (Exception ex)
        {
            response = new Response
            {
                Success = false,
                Message = "Exception.",
            };

            this.logger.Error(ex);
        }


        Response.Clear();
        Response.ContentType = "application/json; charset=utf-8";
        Response.Write(jss.Serialize(response));
        Response.End();
    }
}