using Helpers.Log;
using log4net;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class app_custom_screens_screen_builder_api : System.Web.UI.Page
{
    private JavaScriptSerializer jss = new JavaScriptSerializer();
    private ILog logger = Logger.GetLogger(MethodBase.GetCurrentMethod().DeclaringType.Name);
    private string screensPath = ConfigurationManager.AppSettings["screenBuilderScreensPath"];

    protected void Page_Load(object sender, EventArgs e)
    {
        Response response;

        try
        {
            string action = Request.Form["action"];
            string fileName = Request.Form["filename"];
            string contents = Request.Form["contents"];
            string screenId = Request.Form["screenId"];
            bool global = (Request.Form["global"] != null) ? Convert.ToBoolean(Request.Form["global"]) : false;

            if (action != null)
            {
                switch (action.ToString().ToUpper())
                {
                    case "READXML":
                        response = this.ReadXML(screenId, fileName, global);
                        break;
                    case "WRITEXML":
                        response = this.WriteXML(screenId, fileName, contents, global);
                        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();
    }

    private Response ReadXML(string screenId = null, string fileName = "default", bool global = false)
    {
        Response response;
        try
        {
            fileName = Path.ChangeExtension(fileName, "xml"); 
            string basedir = AppDomain.CurrentDomain.BaseDirectory;
            string folderTemplate = (global) ? ("global") : ("{screenId}").Replace("{screenId}", screenId);
            string directory = folderTemplate; 
            string path = Path.Combine(basedir, screensPath, directory, fileName);
            string webPath = Path.Combine(Request.ApplicationPath, screensPath, directory, fileName).Replace("\\", "/");

            string contents = string.Empty;
            if (File.Exists(path))
            {
                contents = File.ReadAllText(path);

                response = new Response
                {
                    Success = true,
                    Data = new
                    {
                        Path = webPath,
                        Contents = contents
                    }
                };
            }
            else
            {
                response = new Response
                {
                    Success = false,
                    Message = "Error: File does not exist."
                };
            }
        }
        catch (Exception ex)
        {
            response = new Response
            {
                Success = false,
                Message = "Exception.",
            };
            this.logger.Error(ex);
        }

        return response;
    }

    private Response WriteXML(string screenId = null, string fileName = "default", string contents = "", bool global = false)
    {
        Response response;
        try
        {
            fileName = Path.ChangeExtension(fileName, "xml"); 
            string basedir = AppDomain.CurrentDomain.BaseDirectory;
            string folderTemplate = (global) ? ("global") : ("{screenId}").Replace("{screenId}", screenId);
            string directory = folderTemplate; 
            string path = Path.Combine(basedir, screensPath, directory, fileName);
            string webPath = Path.Combine(Request.ApplicationPath, screensPath, directory, fileName).Replace("\\", "/");

            File.WriteAllText(path, contents);

            response = new Response
            {
                Success = true,
                Data = new
                {
                    Path = webPath,
                    Contents = contents
                }
            };
        }
        catch (Exception ex)
        {
            response = new Response
            {
                Success = false,
                Message = "Exception.",
            };
            this.logger.Error(ex);
        }

        return response;
    }
}