<?php

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

 namespace Apps\Mooc\Helper;

use Core\App\AppManager;
use Core\Core\Core;
use Core\Dashboard\DashBoard;
use Core\Entity\Entity\Argument;
use Core\Utility\Date\Date;
use Core\Utility\Format\Format;

use Apps\Mooc\Entity\MoocCategory;
use Apps\Mooc\Entity\MoocLesson;
use Apps\Mooc\Entity\MoocMooc;
use Apps\Mooc\Entity\MoocMoocUser;
use Apps\Mooc\Widget\MoocMoocForm\MoocMoocForm;
use Apps\Mooc\Widget\MoocLessonForm\MoocLessonForm;


class MoocHelper
{
    /**
     * Get All category
     */
    public static function GetCategory($core){

        $category = new MoocCategory($core);
        //$category->Select("Mooc.Name", "MoocName");
        //$category->Join("MoocMooc", "Mooc", "LEFT", "Mooc.CategoryId = MoocCategory.Id");

        return $category->Find(" Id > 0");
    }

    /*
     *  Get All Mooc 
     */
    public static function GetAll($core, $array = false)
    {
        $mooc = new MoocMooc($core);
        $moocs = $mooc->GetAll();
                
        if($array){
            return $mooc->ToAllArray($moocs);
        } else {
        
            return $moocs;
        }
    }
    
    /*
     * Sauvegarde un Mooc
     */
    public static function SaveMooc($core, $data)
    {
        $moocForm = new MoocMoocForm($core, $data);

        if ($moocForm->Validate($data)) {

            $mooc = new MoocMooc($core);

            if ($data["Id"] != "") {
                $mooc->GetById($data["Id"]);
            } else {
                 $mooc->Code->Value = Format::ReplaceForUrl($data["Name"]);
                $mooc->DateCreated->Value = Date::Now();
                $mooc->UserId->Value = $core->User->IdEntite;
            }

            $moocForm->Populate($mooc);
            $mooc->Save();
            
            if($data["Id"] == ""){
                $mooc->IdEntite = $core->Db->GetInsertedId();
            }
            $mooc->SaveImage($data["dvUpload-UploadfileToUpload"], true);
           
            return true;
        }

        return false;
    }
    
    /***
     * Delete a Mooc
     */
    public static function DeleteMooc($core, $moocId){
        
        $mooc = new MoocMooc($core);
        $mooc->GetById($moocId);
        foreach($mooc->GetLessons() as $lesson){
            $lesson->Delete();
        }
        
        $mooc->Delete();
        
        return true;
    }
    
    /**
     * Obtient les Mooc créer par l'utilisateur
     * @param type $core
     */
    public static function GetByUser($core, $returnTab= false)
    {
        $mooc = new MoocMooc($core);
        $mooc->AddArgument(new Argument("Apps\Mooc\Entity\MoocMooc", "UserId", EQUAL, $core->User->IdEntite));
        $moocs = $mooc->GetByArg();
        
        if(count($moocs) > 0 || (count($moocs) == 0 && $returnTab == false))
        {
            return $moocs;
        }
        else
        {
            return array();   
        }
    }
    
     /**
     * Obtient les leçons du Mooc
     * @param type $core
     */
    public static function GetLesson($core, $moocId, $returnTab= false, $actif = null)
    {
        $lesForm = array();
    
        $lesson = new MoocLesson($core);
        $lesson->AddArgument(new Argument("Apps\Mooc\Entity\MoocLesson", "MoocId", EQUAL, $moocId));
           
        if($actif != null)
        {
            $lesson->AddArgument(new Argument("Apps\Mooc\Entity\MoocLesson", "Actif", EQUAL, $actif));
        }
         
        $lessons = $lesson->GetByArg();
         
        if(count($lessons) > 0 || (count($lessons) == 0 && $returnTab == false))
        {
            return $lessons;
        }
        else
        {
            return array();   
        }
    }
    
    /*
     * Sauvegarde une lesson
     */
    public static function SaveLesson($core, $data)
    {
        $moocLessonForm = new MoocLessonForm($core, $data);

        if ($moocLessonForm->Validate($data)) {

            $mooc = new MoocLesson($core);

            if ($data["Id"] != "") {
                $mooc->GetById($data["Id"]);
                $lessonId = $data["Id"];
            } else {
                $mooc->Code->Value = Format::ReplaceForUrl($data["Name"]);
                $mooc->Actif->Value = 1;
            }
         
            $moocLessonForm->Populate($mooc);
            $mooc->Save();
            
            return true;
        }

        return false;
    }
    
    /***
     * Delete a lesson
     */
    public static function RemoveLesson($core, $lessonId){
        
        $moocLesson = new MoocLesson($core);
        $moocLesson->GetById($lessonId);
        $moocLesson->Delete();
        
        return true;
    }
    
    /*
     * Recherche les mooc
     */
    public function Search($core, $categoryId) 
    {
        $mooc = new MoocMooc($core);
        $mooc->AddArgument(new Argument("Apps\Mooc\Entity\MoocMooc", "CategoryId", EQUAL, $categoryId));
        
        return $mooc->GetByArg();
    }
    
    /**
     * Enregistre un formulaire
     * @param type $core
     * @param type $libelle
     * @param type $commentaire
     * @param type $projetId
     */
    public static function SaveQuiz($core, $libelle, $commentaire, $moocId )
    {
        $form = DashBoard::GetApp("Form", $core);
        
        $form->SaveByApp("Mooc", "Apps\Mooc\Entity\MoocMooc", $moocId, $libelle, $commentaire);
    }
    
    /*
     * Sauvegare un mooc pour un utilisateur
     */
    public static function Memorise($core, $userId, $moocId)
    {
        if(!MoocHelper::UserHave($core, $userId, $moocId))
        {
            $moocUser = new MoocMoocUser($core);
            $moocUser->MoocId->Value = $moocId;
            $moocUser->UserId->Value = $userId;
            
            $moocUser->Save();
        }
    }
   
    /*
     * Verifie si l'utilisateur à déjà commencer le Mooc
     */
    public static function UserHave($core, $userId, $moocId)
    {
        $moocUser = new MoocMoocUser($core);
        $moocUser->AddArgument(new Argument("Apps\Mooc\Entity\MoocMoocUser", "UserId", EQUAL, $userId));
        $moocUser->AddArgument(new Argument("Apps\Mooc\Entity\MoocMoocUser", "MoocId", EQUAL, $moocId));
  
        return (count($moocUser->GetByArg())> 0);
    }
    
    /*
     * Récupere les mooc de l utilisateur
     */
    public static function GetStartedByUser($core, $userId)
    {
        $moocUser = new MoocMoocUser($core);
        $moocUser->AddArgument(new Argument("Apps\Mooc\Entity\MoocMoocUser", "UserId", EQUAL, $userId));
        
        return $moocUser->GetByArg();
    }
    
      /**
     * Obtient les images du blog
     * 
     * @param type $core
     * @param type $blogId
     */
    public static function GetImages($core, $moocId)
    { 
        $directory = "Data/Apps/Mooc/". $moocId;
        $nameFile = array();
        $nameFileMini = array();
        
        if ($dh = opendir($directory))
         { $i=0;
         
             while (($file = readdir($dh)) !== false )
             {
               if($file != "." && $file != ".." && substr_count($file,"_96") == 0 )
               {
                   $nameFile[$i] = $core->GetPath("/".$directory."/".$file);
                   $nameFileMini[$i] = $core->GetPath("/".$directory."/".$file."_96.jpg");
                   
                   $i++;
               }
             }
         }
         
         return implode("," , $nameFile) . ";".implode(",", $nameFileMini);
    }
    
    /*
     * Ajoute un elemet à une lesson
     */    
    public function AddElement($core, $lessonId, $type, $name)
    {
        switch($type)
        {
            case 0 :
                $eform = AppManager::GetApp("Form");
                $eform->SaveByApp("Mooc", "MoocLesson", $lessonId, $name, "" );
            break;
        }
    }
    
    /***
     * Obtient le détail d'un mooc
     */
    public static function GetDetail($core, $moocId){
         $mooc = new MoocMooc($core);
         $mooc->GetById($moocId);
        
         $lesson = new MoocLesson($core);
         $lessons = $lesson->Find("MoocId=" . $moocId);
         
         return array("mooc" => $mooc->ToArray(), "lessons" => $lesson->ToAllArray($lessons));        
    }
    
    /***
     * Add User for a Mooc
     */
    public static function AddUser($core, $moocId){
        
        $userId = $core->User->IdEntite;
        
        if(!self::HaveMooc($core, $moocId, $userId)){
            
          $MoocMoocUser = new MoocMoocUser($core);
          $MoocMoocUser->MoocId->Value = $moocId;
          $MoocMoocUser->UserId->Value = $core->User->IdEntite;
          $MoocMoocUser->Save();
        }
    }
    
    /***
     * 
     */
    public static function HaveMooc($core, $moocId, $userId){
        
        $MoocMoocUser = new MoocMoocUser($core);
        $haveMooc = $MoocMoocUser->Find("MoocId=" . $moocId . " AND UserId = " . $userId);
        
        return count($haveMooc) > 0;
    }
    
      /***
     * 
     */
    public static function RemoveUser($core, $moocUserId){
        
        $MoocMoocUser = new MoocMoocUser($core);
        $MoocMoocUser->GetById($moocUserId);
        $MoocMoocUser->Delete();
        return true;
    }

    /**
     * GetLast Mooc
     */
    public static function GetLast($core){

        $mooc = new MoocMooc($core);
        $lastMooc = $mooc->Find("id > 0 ORDER BY Id DESC");
        
        if(count($lastMooc)> 0){           
         return $lastMooc[0];
        } 
        
        return null;
    }
}