<?php

namespace Apps\Admin\Helper;

use Apps\EeApp\Entity\EeWidgetUser;
use Apps\EeApp\Entity\EeAppApp;


class UserWidgetHelper{


    /***
     * Ajoute un widget au tableau de bord de l'utilisateur
     */
    public static function AddWidget($core, $data){

        $widgetUser = new EeWidgetUser($core);
        $widgetUser->Ordre->Value = self::GetNextOrder($core);
        $widgetUser->UserId->Value = $core->User->IdEntite;
        $widgetUser->AppId->Value = $data["AppId"];
        $widgetUser->Save();
    }

    /***
     * Obtient l'ordre suivant
     */
    public static function GetNextOrder($core){

        echo $request = "Select max(Ordre) as nextOrder FROM EeWidgetUser Where UserId = " . $core->User->IdEntite;
        $result = $core->Db->GetLine($request);

        if($result["nextOrder"]) {
            return ((int)$result["nextOrder"]) + 1;
        } else{
            return 1;
        }
    }

    /***
     * Obtient les widgets de l'utilisateur
     */
    public static function GetByUser($core){
        $widgetUser = new EeWidgetUser($core);
        $widgets = $widgetUser->Find("UserId=" . $core->User->IdEntite);

        $apps = array();

        foreach($widgets as $widget){
            $apps[] = $widget->App->Value ;   
        }

        return $apps;
    }

    /**
     * Supprime un widget du tableau de bord utilisateu
     */
    public static function RemoveWidget($core, $data){

        $app = new EeAppApp($core);
        $app = $app->GetByName($data["appName"]);

        $widgetUser = new EeWidgetUser($core);
        $widgets = $widgetUser->Find("AppId=" . $app->IdEntite . " AND UserId=" . $core->User->IdEntite);

        $widgets[0]->Delete();
    }
}
