var EeApp = function () {};

/*
 * Chargement de l'application
 */
EeApp.Load = function (parameter)
{
    this.LoadEvent();

    //Chargement des app de l'utilisateur
    EeAppAction.LoadMyApp();
};

/*
 * Chargement des �venements
 */
EeApp.LoadEvent = function ()
{
    Dashboard.AddEventAppMenu(EeApp.Execute, "", "EeApp");
    Dashboard.AddEventWindowsTool("EeApp");
    
      Event.AddById("btnUpdateFramework", "click", () => {

        Animation.Confirm(Language.GetCode("EeApp.ConfirmUpdateFramework"), function () {

            var data = "Class=EeApp&Methode=UpdateFramework&App=EeApp";

            Request.Post("Ajax.php", data).then(data => {
                Animation.Notify(Language.GetCode("EeApp.FrameworkUpdated"));
            });
            
            data = "Class=EeApp&Methode=UpdateApp&App=EeApp";
            data +="&app=Base";
            Request.Post("Ajax.php", data).then(data => {
                Animation.Notify(Language.GetCode("EeApp.AppUpdated"));
            });
            
        });
    });
};

/*
 * Execute une fonction
 */
EeApp.Execute = function (e)
{
    //Appel de la fonction
    Dashboard.Execute(this, e, "EeApp");
    return false;
};

/*
 *	Affichage de commentaire
 */
EeApp.Comment = function ()
{
    Dashboard.Comment("EeApp", "1");
};

/*
 *	Affichage de a propos
 */
EeApp.About = function ()
{
    Dashboard.About("EeApp");
};

/*
 *	Affichage de l'aide
 */
EeApp.Help = function ()
{
    Dashboard.OpenBrowser("EeApp", "{$BaseUrl}/Help-App-EeApp.html");
};

/*
 *	Affichage de report de bug
 */
EeApp.ReportBug = function ()
{
    Dashboard.ReportBug("EeApp");
};

/*
 * Fermeture
 */
EeApp.Quit = function ()
{
    Dashboard.CloseApp("", "EeApp");
};

/**
 * Evenement utilisateur
 * @returns {undefined}
 */
EeAppAction = function () {};

/**
 * Charge les applications de l'utilisateurs
 * @returns {undefined}
 */
EeAppAction.LoadMyApp = function ()
{
    var data = "Class=EeApp&Methode=LoadMyApp&App=EeApp";
    Dashboard.LoadControl("dvDesktop", data, "", "div", "EeApp");
};

/**
 * Charge les applications disponibles
 * @returns {undefined}
 */
EeAppAction.LoadApps = function ()
{
    var data = "Class=EeApp&Methode=LoadApps&App=EeApp";
    Dashboard.LoadControl("dvDesktop", data, "", "div", "EeApp");
};

/**
 * Charge les applications disponibles
 * @returns {undefined}
 */
EeAppAction.LoadApps = function ()
{
    var data = "Class=EeApp&Methode=LoadApps&App=EeApp";
    Dashboard.LoadControl("dvDesktop", data, "", "div", "EeApp");
};

/**
 * Charge les applications disponibles
 * @returns {undefined}
 */
EeAppAction.LoadTemplates = function ()
{
    var data = "Class=EeApp&Methode=LoadTemplates&App=EeApp";
    let cmsWidget = Dom.GetById("cmsWidget");
   
    if(cmsWidget){
        Dashboard.LoadControl("cmsWidget", data, "", "div", "Cms");
    } else{    
         Dashboard.LoadControl("dvDesktop", data, "", "div", "EeApp");
    }
   
};

/**
 * Charge les plugins disponibles
 * @returns {undefined}
 */
EeAppAction.LoadPlugins = function ()
{
    let data = "Class=EeApp&Methode=LoadPlugins&App=EeApp";

    Request.Post("Ajax.php", data).then(data => {

        Animation.Load("dvDesktop", data);

       Event.AddByClass("btnEditPlugin", "click", EeAppAction.EditPlugin);
    });
};

/***
 * Edit a plugin
 */
EeAppAction.EditPlugin = function(e){

    let pluginId = e.srcElement.id;

    Dialog.open('', {"title": Dashboard.GetCode("EeApp.EditPlugin"),
        "app": "EeApp",
        "class": "DialogEeApp",
        "method": "EditPlugin",
        "params": pluginId,
        "type": "right"});
};

/***
 * Define template as default
 * @returns {undefined}
 */
EeAppAction.DefineTemplateActif = function(templateId){
    
    Animation.Confirm(Language.GetCode("EeApp.ConfirmDefineTemplateAction"), function(){
       
         let data = "Class=EeApp&Methode=DefineTemplateActif&App=EeApp";
        data += "&TemplateId="+templateId;
      
        Request.Post("Ajax.php", data).then(data => {
            Animation.Notify(Language.GetCode("EeApp.TemplateChanged"));
            
            EeAppAction.LoadTemplates();
        });
       
    });
};

/**
 * Charge les applications disponibles sur le store
 * @returns {undefined}
 */
EeAppAction.LoadStore = function ()
{
    let data = "Class=EeApp&Methode=GetAppStore&App=EeApp";
    let desktop = document.getElementById("dvDesktop");

   Request.Post("Ajax.php", data).then(data=>{
    
    let view = "<div id='store'>";
    
    data = JSON.parse(data);
    
    let Apps = data.Apps;
    let Plugins = data.Plugins;
    let Templates = data.Templates;
    
    view += "<h1 class='VTabStripEnabled active' id='tab0'>" + Language.GetCode("EeApp.Apps")+  "</h1>";
    view += "<div class='row tabContent' id='content0'>";
    
    view += "<div class='col-md-12' style='padding:5px'><label>" + Language.GetCode("EeApp.Filters")+  "</label><input id='tbSearch' style='width:90%; margin:auto' type='text' class='form form-control' placeHolder='"+ Language.GetCode("EeApp.EnterATextToSearchApp")  +"'/></p></div>";
    
    for(var i = 0; i < Apps.length; i++){
      
        view += "<div class='col-md-3'><div class='appStore'>";
        view += "<h4>" + Apps[i].Name +   "</h4>";
        
        if(Apps[i].Version){
            view += "<b>Version : " + Apps[i].Version +   "</b>";
        }
        
        if(Apps[i].Images.length > 0){
        
            for(let j = 0; j < Apps[i].Images.length ; j++ ){
             
                if(Apps[i].Images[j].indexOf("full") > 0 ){
                    view += "<div style='width:100%; height : 200px;background : url(" + Apps[i].Images[j] + "); background-size:cover' ></div>";
                }
            } 
        }
      
        view += "<p>" + Apps[i].Description+ "</p>";
        view += "<button data-app='"+ Apps[i].Name +"' class='btn btn-primary btnInstallApp'>" + Language.GetCode("EeApp.Install")+"</button>";
        
        view += "</div></div>";
    }

    view += "</div>";
 
    view += "<h1 class='VTabStripEnabled' id='tab2'>" + Language.GetCode("EeApp.Templates")+  "</h1>";
    view += "<div class='row tabContent' id='content2' style='display:none'>";
    
    for(var i = 0; i < Templates.length; i++){
      
        view += "<div class='col-md-3'><div class='appStore'>";
        view += "<h4>" + Templates[i].Name+ "</h4>";
        view += "<p>" + Templates[i].Description+ "</p>";
        
         if(Templates[i].Images.length > 0){
        
            for(let j = 0; j < Templates[i].Images.length ; j++ ){
             
                if(Templates[i].Images[j].indexOf("full") > 0 ){
                    view += "<div style='width:100%; height : 200px;background : url(" + Templates[i].Images[j] + "); background-size:cover' ></div>";
                }
            } 
        }
        
        
        view += "<button data-app='"+ Templates[i].Name +"' class='btn btn-primary btnInstallTemplate'>" + Language.GetCode("EeApp.Install")+"</button>";
        
        view += "</div></div>";
    }
    view += "</div>";
    
    view += "<h1 class='VTabStripEnabled' id='tab1'>" + Language.GetCode("EeApp.Plugins")+  "</h1>";
    view += "<div class='row tabContent' id='content1' style='display:none'>";
   
    for(var i = 0; i < Plugins.length; i++){
      
        view += "<div class='col-md-3'><div class='appStore'>";
        view += "<h4>" + Plugins[i].Name +   "</h4>";
        
        if(Plugins[i].Version){
            view += "<b>Version : " + Plugins[i].Version +   "</b>";
        }
        
        if(Plugins[i].Images.length > 0){
        
            for(let j = 0; j < Plugins[i].Images.length ; j++ ){
             
                if(Plugins[i].Images[j].indexOf("full") > 0 ){
                    view += "<div style='width:100%; height : 200px;background : url(" + Plugins[i].Images[j] + "); background-size:cover' ></div>";
                }
            } 
        }
      
        view += "<p>" + Plugins[i].Description+ "</p>";
        view += "<button data-app='"+ Plugins[i].Name +"' class='btn btn-primary btnInstallPlugin'>" + Language.GetCode("EeApp.Install")+"</button>";
        
        view += "</div></div>";
    }
    
    view += "</div></div>";
   

    desktop.innerHTML = view;
   
    Event.AddByClass("VTabStripEnabled" , "click", function(e){
        
       let VTab = document.querySelectorAll("#store .VTabStripEnabled");
       let VtabContent = document.querySelectorAll("#store .tabContent");
       
        for(let i =0; i < VTab.length; i++){
           VTab[i].className= "VTabStripEnabled";
           VtabContent[i].style.display = "none";
       }
       
        e.srcElement.className = "VTabStripEnabled active";
        let content = document.getElementById(e.srcElement.id.replace("tab", "content"));
            content.style.display = "";
    });

    Event.AddByClass("btnInstallApp", "click", EeAppAction.InstallApp);
    Event.AddByClass("btnInstallPlugin", "click", EeAppAction.InstallPlugin);
    Event.AddByClass("btnInstallTemplate", "click", EeAppAction.InstallTemplate);
    Event.AddById("tbSearch", "keyup", EeAppAction.FilterApp);
    
    });
};

/***
 * Télécharge et Install une application depuis le store 
 */
EeAppAction.InstallApp = function(e){

    const AppName = e.srcElement.dataset.app;

    let data = "Class=EeApp&Methode=InstallApp&App=EeApp";
        data += "&AppName="+AppName;
      
        Request.Post("Ajax.php", data).then(data => {
            Animation.Notify(Language.GetCode("EeApp.ApplicationInstallSuccess"));
        });
};

/***
 * Download and install
 * @param {type} e
 * @returns {undefined}
 */
EeAppAction.InstallPlugin = function(e){
    
    const PluginName = e.srcElement.dataset.app;
     
    let data = "Class=EeApp&Methode=InstallPlugin&App=EeApp";
        data += "&AppName="+PluginName;
      
        Request.Post("Ajax.php", data).then(data => {
            Animation.Notify(Language.GetCode("EeApp.PluginInstallSuccess"));
        });
};

/***
 * Download and install template
 * @param {type} e
 * @returns {undefined}
 */
EeAppAction.InstallTemplate = function(e){
    const TemplateName = e.srcElement.dataset.app;

    let data = "Class=EeApp&Methode=InstallTemplate&App=EeApp";
        data += "&AppName="+TemplateName;
      
        Request.Post("Ajax.php", data).then(data => {
            Animation.Notify(Language.GetCode("EeApp.TemplateInstallSuccess"));
        });
};

/***
 * 
 * @returns {undefined}
 */
EeAppAction.FilterApp = function(e){
 
    let value = e.srcElement.value.toLowerCase();
    let apps = document.querySelectorAll(".appStore");
    
    for(let i =0 ; i < apps.length; i++){
        
        let title = apps[i].getElementsByTagName("h4");
        let description = apps[i].getElementsByTagName("p");
        
        if(title[0].innerHTML.toLowerCase().indexOf(value) > -1 || description[0].innerHTML.toLowerCase().indexOf(value) > -1){
            apps[i].parentNode.style.display = "";
        } else {
            apps[i].parentNode.style.display = "none";
        }
    }
};

/**
 * Ajoute une application au bureau
 * @returns
 */
EeAppAction.Add = function (appId, control)
{
    var JAjax = new ajax();
    JAjax.data = "Class=EeApp&Methode=Add&App=EeApp&appId=" + appId;

    JAjax.GetRequest("Ajax.php");

    control.parentNode.removeChild(control);

    EeAppAction.RefreshAppMenu();
};

/***
 * Met à jour l'application
 * @param {type} appName
 * @param {type} control
 * @returns {undefined}
 */
EeAppAction.UpdateApp = function(appName, control){

Animation.Confirm(Language.GetCode("EeApp.ConfirmUpdateApp"), function () {

        let data = "Class=EeApp&Methode=UpdateApp&App=EeApp";
            data +="&app="+appName;
            Request.Post("Ajax.php", data).then(data => {
                Animation.Notify(Language.GetCode("EeApp.AppUpdated"));
            });
        });
};

//Supprime une application au bureau
EeAppAction.Remove = function (appId, control)
{
    if (confirm(Dashboard.GetCode("ConfirmDelete")))
    {
        var JAjax = new ajax();
        JAjax.data = "Class=EeApp&Methode=Remove&App=EeApp&appId=" + appId;

        JAjax.GetRequest("Ajax.php");
        control.parentNode.parentNode.parentNode.removeChild(control.parentNode.parentNode);

        EeAppAction.RefreshAppMenu();
    }
};

/*
 * Refresh
 * @returns {undefined}
 */
EeAppAction.RefreshAppMenu = function ()
{
    let data = "Class=DashBoardManager&Methode=LoadUserApp&show=1";
    
    Request.Post("Ajax.php", data).then(data => {
        let lstApp = document.getElementById("lstApp");
            lstApp.innerHTML = data;
        Admin.Init();
    });
};

/**
 * Charge la partie Administration des app
 * @returns {undefined}
 */
EeAppAction.LoadAdmin = function ()
{
    var data = "Class=EeApp&Methode=LoadAdmin&App=EeApp";
    Dashboard.LoadControl("dvDesktop", data, "", "div", "EeApp");
};

/**
 * Popin d'ajout d'annonce
 */
EeAppAction.ShowAddApp = function (appId)
{
    var param = Array();
    param['App'] = 'EeApp';
    param['Title'] = 'EeApp.ShowAddApp';

    if (appId != undefined)
    {
        param['appId'] = appId;
    }

    Dialog.open('', {"title": Dashboard.GetCode("EeApp.AddApp"),
        "app": "EeApp",
        "class": "DialogEeApp",
        "method": "ShowAddApp",
        "params": "",
        "type": "right"});
};

/**
 * Pop de gestion des administrateurs
 * @param {type} appId
 * @returns
 */
EeAppAction.ShowAdmin = function (appId)
{
    var param = Array();
    param['App'] = 'EeApp';
    param['Title'] = 'EeApp.ShowAdmin';
    param['appId'] = appId;

    Dashboard.OpenPopUp('EeApp', 'ShowAdmin', '', '', '', 'EeAppAction.LoadAdmin()', serialization.Encode(param));
};

/*
 * Ajoute un administrateur
 */
EeAppAction.AddAdmin = function (appId)
{
    var divResult = document.getElementById("divResult");
    var controls = divResult.getElementsByTagName("input");
    var dvAdmin = document.getElementById("dvAdmin");

    idContact = Array();

    for (i = 0; i < controls.length; i++)
    {
        if (controls[i].type == "checkbox" && controls[i].checked)
        {
            idContact[i] = controls[i].id;
        }
    }

    var JAjax = new ajax();
    JAjax.data = "Class=EeApp&Methode=AddAdmin&App=EeApp&appId=" + appId;
    JAjax.data += "&contactId=" + idContact.join(",");

    dvAdmin.innerHTML = JAjax.GetRequest("Ajax.php");

    Dashboard.CloseSearch();
};

/**
 * Supprime un administrateur d'une application
 * @param {type} id
 * @param {type} control
 * @returns {undefined}
 */
EeAppAction.DeleteAdmin = function (id, control)
{
    if (Dashboard.Confirm("Delete"))
    {
        var JAjax = new ajax();
        JAjax.data = "Class=EeApp&Methode=DeleteAdmin&App=EeApp&adminId=" + id;

        JAjax.GetRequest("Ajax.php");

        control.parentNode.parentNode.removeChild(control.parentNode);
    }
};

/*
 * Pop in pour Ajouter des applications
 */
EeAppAction.ShowUploadApp = function ()
{
    var param = Array();
    param['App'] = 'EeApp';
    param['Title'] = 'EeApp.ShowUploadApp';

    Dashboard.OpenPopUp('EeApp', 'ShowUploadApp', '', '', '', 'EeAppAction.LoadAdmin()', serialization.Encode(param));
};

/*
 * Supprime une app
 */
EeAppAction.RemoveApp = function (control)
{
    if (confirm(Dashboard.GetCode("EeApp.RemoveApp")))
    {
        var JAjax = new ajax();
        JAjax.data = "Class=EeApp&Methode=RemoveApp&App=EeApp&appId=" + control.id;

        JAjax.GetRequest("Ajax.php");

        control.parentNode.parentNode.parentNode.removeChild(control.parentNode.parentNode);
    }
};

/*
 * Pop in pour Ajouter des langues
 */
EeAppAction.ShowUploadLanguage = function ()
{
    var param = Array();
    param['App'] = 'EeApp';
    param['Title'] = 'EeApp.ShowUploadLanguage';

    Dashboard.OpenPopUp('EeApp', 'ShowUploadLanguage', '', '', '', 'EeAppAction.LoadAdmin()', serialization.Encode(param));
};

/***
 * Dialogue de lise a jour des version du coeur et des applications
 */

EeAppAction.ShowUpdateVersion = function () {
    Dialog.open('', {"title": Dashboard.GetCode("EeApp.UpdateVersion"),
        "app": "EeApp",
        "class": "DialogEeApp",
        "method": "ShowUpdateVersion",
        "params": "",
        "type": "right"});

};

/****
 * Dialogue d'ajout de plugin
 * @returns {undefined}
 */
EeAppAction.ShowAddPlugin = function(){
    Dialog.open('', {"title": Dashboard.GetCode("EeApp.AddPlugin"),
        "app": "EeApp",
        "class": "DialogEeApp",
        "method": "ShowAddPlugin",
        "params": "",
        "type": "right"});
}; 

/***
 * Add Template
 * @returns {undefined}
 */
EeAppAction.ShowAddTemplate = function(){
    Dialog.open('', {"title": Dashboard.GetCode("EeApp.AddTemplate"),
        "app": "EeApp",
        "class": "DialogEeApp",
        "method": "ShowAddTemplate",
        "params": "",
        "type": "right"});
};

/***
 * Initialisation du front widget
 * @returns {undefined}
 */
EeApp.Init = function(){
    
};

/***
 * Initialisation du widget Admin
 * @returns {undefined}
 */
EeApp.InitAdminWidget = function () {
};
