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_configuration_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"];
    private string connectionString = ConfigurationManager.ConnectionStrings["SYSTEM"].ConnectionString;

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

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

            if (action != null)
            {
                switch (action.ToString().ToUpper())
                {
                    case "GET_UPLOADED_FILES":
                        response = this.GetUploadedFiles(screenId, global, extensions); 
                        break;
                    case "UPLOAD_FILE":
                        response = this.CheckFileUpload(screenId, global); 
                        break; 
                    case "REMOVE_FILE":
                        response = this.RemoveFiles(screenId, global); 
                        break; 
                    case "CREATE_SCREEN":
                        response = this.CreateScreen(screenId); 
                        break; 
                    case "REMOVE_SCREEN":
                        response = this.RemoveScreen(screenId); 
                        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 CreateScreen(string screenId)
    {
        Response response;
        try
        {
            string basedir = AppDomain.CurrentDomain.BaseDirectory;
            string dirName = ("{screenId}").Replace("{screenId}", screenId);
            string path = Path.Combine(basedir, screensPath, dirName);

            if (Directory.Exists(path))
            {
                Directory.Delete(path, true); 
            }

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
                //Directory.CreateDirectory(Path.Combine(path, "files"));
                File.WriteAllText(Path.Combine(path, "screen.html")
                    , 
                    @"
                    <!-- Set your background color -->
                    <config data-backgroundColor='white' />
                    
                    "
                );

                response = new Response
                {
                    Success = true,
                    Data = new {
                        Id = screenId
                    }
                };
            }
            else {
                response = new Response
                {
                    Success = false,
                    Message = "DIRECTORY_ALREADY_EXISTS"
                };
            }
        }
        catch (Exception ex)
        {
            response = new Response
            {
                Success = false,
                Message = "Exception.",
            };
            this.logger.Error(ex);
        }

        return response; 
    }

    private Response RemoveScreen(string screenId)
    {
        Response response;
        try
        {
            string basedir = AppDomain.CurrentDomain.BaseDirectory;
            string dirName = ("{screenId}").Replace("{screenId}", screenId);
            string path = Path.Combine(basedir, screensPath, dirName);

            if (Directory.Exists(path))
            {
                Directory.Delete(path, true);
                
                response = new Response
                {
                    Success = true,
                    Data = new
                    {
                        Id = screenId
                    }
                };
            }else{
                response = new Response
                {
                    Success = false,
                    Message = "DIRECTORY_NOT_FOUND"
                };
            }
        }
        catch (Exception ex)
        {
            response = new Response
            {
                Success = false,
                Message = "Exception.",
            };
            this.logger.Error(ex);
        }

        return response;
    }

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

            HttpFileCollection fileCollection = Request.Files;
            if (fileCollection.Count > 0)
            {
                for (int finx = 0; finx < fileCollection.Count; finx++)
                {
                    HttpPostedFile file = fileCollection[finx]; 
                    string filename = Path.Combine(path, file.FileName);
                    file.SaveAs(filename);
                }

                response = new Response
                {
                    Success = true,
                    Data = new { }
                }; 
            }
            else
            {
                response = new Response
                {
                    Success = false,
                    Message = "No file was sent in request."
                }; 
            }
        }
        catch (Exception ex) {
            response = new Response
            {
                Success = false,
                Message = "Exception.",
            };
            this.logger.Error(ex); 
        }

        return response; 
    }

    private Response RemoveFiles(string screenId = null, bool global = false)
    {
        Response response;
        try
        {
            List<string> files = Request.Form["files"].Split(';').ToList(); 
            string basedir = AppDomain.CurrentDomain.BaseDirectory;
            //string dirName = ("{screenId}").Replace("{screenId}", screenId);
            string folderTemplate = (global) ? ("global") : ("{screenId}").Replace("{screenId}", screenId);
            string dirName = folderTemplate; 
            string path = Path.Combine(basedir, screensPath, dirName);
            string webPath = Path.Combine(Request.ApplicationPath, screensPath, dirName).Replace("\\", "/");

            if (Directory.Exists(path))
            {
                foreach (var file in files)
                {
                    string filePath = Path.Combine(path, file);
                    if (File.Exists(filePath))
                    {
                        File.Delete(filePath); 
                    }
                }
            }

            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; 
    }

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

            List<string> validExtensions = (extensions != null) ? extensions.Split(',').ToList() : new List<string>();
            validExtensions = validExtensions.ConvertAll(d => d.Trim().ToUpper()); 

            //List<string> files = new List<string>(); 
            Dictionary<string, string> files = new Dictionary<string, 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.Replace(".", "").ToUpper())) validFile = false;
                    }

                    if (info.Name != "screen.html" && validFile) files.Add(info.Name, webPath + '/' + info.Name); //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; 
    }
}