<?php

/*
 * PuzzleApp
 * Webemyos
 * Jérôme Oliva
 * GNU Licence
 */

namespace Apps\EeApp\Helper;

use Core\Core\Core;
use Core\Entity\Entity\Argument;
use Apps\EeApp\Entity\EeAppUser;
use Apps\EeApp\Entity\EeAppApp;
use Apps\EeApp\Entity\EeAppPlugin;
use Apps\EeApp\Entity\EeAppTemplate;
use Apps\EeApp\Entity\EeAppAdmin;
use Core\Utility\File\File;
use Core\Utility\Format\Format;

class UploadHelper {
    /*
      Add the App to the systéme
     */

    public static function DoUploadApp($fileName, $tmpFileName) {

        $core = Core::getInstance();
        $appName = str_replace(".zip", "", $fileName);

        $fileName = "Data/Tmp/$appName.zip";
        $message .= "1.Decompression";
        
        File::UnCompresse("Data/Tmp/$appName", "$appName.zip");

        $message .= "2.Suppression $appName.zip";
        File::Delete("$appName.zip", "Data/Tmp/$appName");

        $message .= "3.Copy des bon fichier";
        File::copyfolder("Data/Tmp/$appName/", "../Apps/$appName/");

        $message .= "4.Suppression";
        File::RemoveAllDir("Data/Tmp/$appName/");

        $appExist = new EeAppApp($core);

        $app = $appExist->Find("Name='" . $appName . "'");

        if (count($app) == 0) {

            $message .= "5.Script sql";
            $request = File::GetFileContent("../Apps/" . $appName . "/Db/install.sql");
            $core->Db->ExecuteMulti($request);

            $message .= "6.Ajout en bdd";

            //Ajout dans la base de donnée
            $AppApp = new EeAppApp($core);
            $AppApp->Name->Value = $appName;
            $AppApp->CategoryId->Value = 1;
            $AppApp->Save();
            
            
            $App = \Core\Dashboard\DashBoardManager::GetApp($appName, $core);
            $App->PostInstall();
            
        }
        
        $message .= "7.Traduction";
        $langFile = "../Apps/$appName/Lang/langFr.json";
        self::DoUploadLanguage("", "", $langFile);
       
        $langFile = "../Apps/$appName/Lang/langEn.json";
        self::DoUploadLanguage("", "", $langFile);
       
        echo $message;
        return;
    }

    /*
      Add the App to the systéme
     */

    public static function DoUploadLanguage($fileName, $tmpFileName, $packageFile = "") {
        $core = Core::getInstance();

        if ($fileName != "") {
            if (move_uploaded_file($tmpFileName, __DIR__ . "/../../" . $fileName)) {
                echo "<br/> Can't move de file";
            }

            $data = json_decode(File::GetFileContent(__DIR__ . "/../../" . $fileName));
        } else {
            $data = json_decode(File::GetFileContent($packageFile));
        }

        $codeLang = $data->lang;

        $request = "SELECT Id FROM ee_lang where Code='" . $codeLang . "'";
        $result = $core->Db->GetLine($request);
        $langId = $result["Id"];

        foreach ($data->data as $element) {

            $request = "SELECT Id FROM ee_lang_code where Code='" . $element->Code . "'";
            $result = $core->Db->GetLine($request);

            if ($result == null) {
                $request = "INSERT INTO ee_lang_code(Code) VALUES ('" . $element->Code . "' )";
                $core->Db->Execute($request);
            }

            $request = "SELECT Id FROM ee_lang_element where CodeId=(select Id from ee_lang_code where code = '" . $element->Code . "' limit 0,1) AND LangId=" . $langId;
            $result = $core->Db->GetLine($request);

            if ($result == null) {
                $request = "INSERT INTO ee_lang_element (CodeId, LangId, Libelle) values ";
                $request .= "(( select Id from ee_lang_code where code = '" . $element->Code . "' limit 0,1), " . $langId . " , '" . Format::EscapeString($element->Libelle) . "');";
                $core->Db->Execute($request);
            }
        }


        echo "<br/>Suppression de l'archive : " . $fileName;
        File::Delete($fileName, __DIR__ . "/../../");
    }

    /*     * *
     * Add Plugin to the systeme
     */

    public static function DoUploadPlugin($fileName, $tmpFileName) {
        $core = Core::getInstance();
        $appName = str_replace(".zip", "", $fileName);

        $fileName = "Data/Tmp/$appName.zip";
        $message .= "1.Decompression";
        File::UnCompresse("Data/Tmp/$appName", "$appName.zip");

        $message .= "2.Suppression $appName.zip";
        File::Delete("$appName.zip", "Data/Tmp/$appName");

        $message .= "3.Copy des bon fichier";
        File::copyfolder("Data/Tmp/$appName/", "../Plugins/$appName/");

        $message .= "4.Suppression";
        File::RemoveAllDir("Data/Tmp/$appName/");

        $appExist = new EeAppPlugin($core);

        $app = $appExist->Find("Name='" . $appName . "'");

        if (count($app) == 0) {

            $message .= "5.Script sql";
            $request = File::GetFileContent("../Plugins/" . $appName . "/Db/install.sql");
            $core->Db->ExecuteMulti($request);

            $message .= "6.Ajout en bdd";

            //Ajout dans la base de donnée
            $AppApp = new EeAppPlugin($core);
            $AppApp->Name->Value = $appName;
            $AppApp->Code->Value = $appName;
            $AppApp->Description->Value = $appName;
            $AppApp->Save();
        }

        echo $message;
        return;
    }

    /*     * *
     * Add Template to the systeme
     */

    public static function DoUploadTemplate($fileName, $tmpFileName) {
        $core = Core::getInstance();
        $appName = str_replace(".zip", "", $fileName);

        $fileName = "Data/Tmp/$appName.zip";
        $message .= "1.Decompression";
        File::UnCompresse("Data/Tmp/$appName", "$appName.zip");

        $message .= "2.Suppression $appName.zip";
        File::Delete("$appName.zip", "Data/Tmp/$appName");

        $message .= "3.Copy des bon fichier";
        File::copyfolder("Data/Tmp/$appName/", "../Templates/$appName/");

        $message .= "4.Suppression";
        File::RemoveAllDir("Data/Tmp/$appName/");

        $appExist = new EeAppTemplate($core);

        $app = $appExist->Find("Name='" . $appName . "'");

        if (count($app) == 0) {

            $message .= "5.Ajout en bdd";

            //Ajout dans la base de donnée
            $AppApp = new EeAppTemplate($core);
            $AppApp->Name->Value = $appName;
            $AppApp->Code->Value = $appName;
            $AppApp->Description->Value = $appName;
            $AppApp->Save();
        }

        echo $message;
        return;
    }
    
    /*     * **
     * Met à jour du dossier Core depuis le temps 
     */

    public static function DoUpdateFramework($core) {

        $message = "1.Upload Framework";
        File::CreateDirectory("Data/Tmp/EeApp/");
        File::CreateDirectory("Data/Tmp/EeApp/Core/");

        $url = $core->Config->GetKey("puzzleAppUrl");
        $url .= "Downloader/Download/Core";
        $package = file_get_contents($url, false);

        //Enregistrement temp
        $message .= "2.Enregistrement";
        file_put_contents("Data/Tmp/EeApp/Core/Core.zip", $package);
        chmod("Data/Tmp/EeApp/Core/Core.zip", 0777);

        $fileName = "Data/Tmp/EeApp/Core/Core.zip";
        $message .= "3.Decompression";
        File::UnCompresse("Data/Tmp/EeApp/Core", "Core.zip");

        $message .= "4.Suppression core.zip";
        File::Delete("Core.zip", "Data/Tmp/EeApp/Core");

        $message .= "5.Copy des bon fichier";
        File::copyfolder("Data/Tmp/EeApp/Core/", "../Core/");

        $message .= "6.Suppression";
        File::RemoveAllDir("Data/Tmp/EeApp/Core/");

        return $message;
    }

    /*     * **
     * Met à jour le dossier d'une App
     */

    public static function DoUpdateApp($core, $app) {

        $message = "1.Upload Framework";
        File::CreateDirectory("Data/Tmp/EeApp/");
        File::CreateDirectory("Data/Tmp/EeApp/$app/");

        $url = $core->Config->GetKey("puzzleAppUrl");
        $url .= "Downloader/Download/$app";
        $package = file_get_contents($url, false);

        //Enregistrement temp
        $message .= "2.Enregistrement";
        file_put_contents("Data/Tmp/EeApp/$app/$app.zip", $package);
        chmod("Data/Tmp/EeApp/$app/$app.zip", 0777);

        $message .= "3.Decompression";
        File::UnCompresse("Data/Tmp/EeApp/$app", "$app.zip");

        $message .= "4.Suppression core.zip";
        File::Delete("$app.zip", "Data/Tmp/EeApp/$app");

        $message .= "5.Copy des bon fichier";
        File::copyfolder("Data/Tmp/EeApp/$app/", "../Apps/$app/");

        $message .= "6.Suppression";
        File::RemoveAllDir("Data/Tmp/EeApp/$app/");

        $message .= "7.Traduction";
        $langFile .= "../Apps/$app/Lang/langFr.json";

        if (!file_exists($langFile)) {
            $message .= "Pas trouvé";
        } else {

            self::DoUploadLanguage("", "", $langFile);
        }
        return $message;
    }
}
