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_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"];
            string extensions = Request.Form["extensions"]; 

            if (action != null)
            {
                switch (action.ToString().ToUpper())
                {
                    case "READ":
                        response = (string.IsNullOrEmpty(fileName)) ? this.ReadFile(screenId:screenId) : this.ReadFile(screenId, fileName); 
                        break;
                    case "WRITE":
                        response = (string.IsNullOrEmpty(fileName)) ? this.WriteFile(screenId:screenId, contents:contents) : this.WriteFile(screenId, fileName, contents); 
                        break;
                    case "GET_UPLOADED_FILES":
                        response = this.GetUploadedFiles(screenId, extensions);
                        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 WriteFile(string screenId = null, string fileName = "screen.html", string contents = "")
    {
        Response response;
        try
        {
            //string path = screensPath + fileName;
            //string path = Request.ApplicationPath + screensPath + fileName; 
            string basedir = AppDomain.CurrentDomain.BaseDirectory;
            string directory = (!String.IsNullOrEmpty(screenId)) ? ("{screenId}").Replace("{screenId}", screenId) : string.Empty; 
            string path = Path.Combine(basedir, screensPath, directory, fileName);
            string webPath = Path.Combine(Request.ApplicationPath, screensPath, directory, fileName).Replace("\\", "/");

            if (File.Exists(path))
            {
                File.WriteAllText(path, contents); 

                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 ReadFile(string screenId = null, string fileName = "screen.html")
    {
        Response response; 
        try
        {
            //string path = screensPath + fileName;
            //string path = Request.ApplicationPath + screensPath + fileName; 
            string basedir = AppDomain.CurrentDomain.BaseDirectory;
            string directory = (!String.IsNullOrEmpty(screenId)) ? ("{screenId}").Replace("{screenId}", screenId) : string.Empty; 
            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 GetUploadedFiles(string screenId, string extensions = null)
    {
        Response response;
        try
        {
            string basedir = AppDomain.CurrentDomain.BaseDirectory;
            string dirName = ("{screenId}").Replace("{screenId}", screenId);
            string path = Path.Combine(basedir, screensPath, dirName);
            List<string> validExtensions = (extensions != null) ? extensions.Split(',').ToList() : new List<string>(); 
            validExtensions.ForEach(t => t.ToUpper()); 

            List<string> files = new List<string>();
            if (Directory.Exists(path))
            {
                foreach (var file in Directory.GetFiles(path))
                {
                    FileInfo info = new FileInfo(file);
                    bool validFile = true; 
                    if (validExtensions.Count > 0){
                        if (!validExtensions.Contains(info.Extension)) validFile = false;  
                    }
                    
                    if (info.Name != "screen.html") files.Add(info.Name);
                }
            }

            response = new Response
            {
                Success = true,
                Data = new
                {
                    Files = files
                }
            };
        }
        catch (Exception ex)
        {
            response = new Response
            {
                Success = false,
                Message = "Exception.",
            };
            this.logger.Error(ex);
        }

        return response;
    }
}