<?php

namespace Cadoles\CoreBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

use Cadoles\PortalBundle\Entity\Bookmark;

class RestController extends Controller
{
    // rest/login
    // Permet de tester l'accès à ninegate
    // key = parametre obligatoire
    // key = clé d'accès de l'api
    public function loginAction(Request $request)
    {
        $key=$request->get('key');
        $output=[];

        // Vérification de la clé
        $realkey = $this->getParameter("apikeyninegate");
        if($key!=$realkey) {
            $output["error"]="error key";
            return new Response(json_encode($output), 400);
        }
        
        return new Response(json_encode($output), 200);
    }

    // rest/user/{login}
    // Récupération des informations utilisateurs issus du masteridentity
    // key = parametre obligatoire
    // key = clé d'accès de l'api
    // only = paramétre optionnel
    // only = liste des informations désirés = user, items, bookmarks, groups, alerts, calendars    
    // ssoitems = paramétre optionnel
    // ssoitems = liste des items issu du ssoitems

    public function userAction($login, Request $request)
    {
        $key=$request->get('key');
        $only=($request->get('only')?explode(",",$request->get('only')):"");
        $ssoitems=($request->get('ssoitems')?explode(",",$request->get('ssoitems')):[]);

        // Vérification de la clé
        $realkey = $this->getParameter("apikeyninegate");
        if($key!=$realkey) {
            $output["error"]="error key";
            return new Response(json_encode($output), 400);
        }

        $em = $this->getDoctrine()->getManager();
        $output = [];

        // Récupérer l'utilisateur
        $user=$em->getRepository('CadolesCoreBundle:User')->findOneBy(["username"=>$login]);
        if(!$user) {
            $output["error"]="user not exist";
            return new Response(json_encode($output), 400);
        }

        // Format de sortie
        if($only==""||in_array("user",$only))           $output["user"]             = [];
        if($only==""||in_array("bookmarks",$only))      $output["bookmarks"]        = [];
        if($only==""||in_array("items",$only))          $output["items"]            = [];
        if($only==""||in_array("items",$only))          $output["itemcategorys"]    = [];
        if($only==""||in_array("groups",$only))         $output["groups"]           = [];
        if($only==""||in_array("alerts",$only))         $output["alerts"]           = [];
        if($only==""||in_array("alerts",$only))         $output["alertcategorys"]   = [];
        if($only==""||in_array("calendars",$only))      $output["calendars"]        = [];
        if($only==""||in_array("calendars",$only))      $output["calendarevents"]   = [];
        
        $bookmarks=null;
        $items=null;
        $itemcategorys=null;
        $weburl="https://".$this->getParameter("weburl")."/".$this->getParameter("alias")."/";

        $em->getRepository("CadolesPortalBundle:Item")->getUserItems($user,$bookmarks,$items,$itemcategorys,null,$ssoitems,4);
        //$this->getDoctrine()->getRepository("CadolesPortalBundle:Page")->getPagesUser($user,null,$entity,$pagesuser,$pagesadmin,$groupsshared);

        // Construction de la réponse
        if($only==""||in_array("user",$only)) {
            $output["user"]["firstname"]    = $user->getFirstname();
            $output["user"]["lastname"]     = $user->getLastname();
            $output["user"]["email"]        = $user->getEmail();
            $output["user"]["avatar"]       = $weburl."uploads/avatar/".$user->getAvatar();
            $output["user"]["niveau01"]     = $user->getNiveau01()->getLabel();
            $output["user"]["niveau02"]     = ($user->getNiveau02()?$user->getNiveau02()->getLabel():null);
            $output["user"]["role"]         = $user->getRole();
        }

        if($only==""||in_array("bookmarks",$only)) {
            if($bookmarks) {
                foreach($bookmarks as $bookmark) {
                    $tmp=[];
                    $tmp["id"]          = $bookmark->getId();
                    $tmp["title"]       = $bookmark->getTitle();
                    $tmp["url"]         = $bookmark->getUrl();
                    $tmp["target"]      = $bookmark->getTarget();
                    $tmp["item"]        = ($bookmark->getItem()?$bookmark->getItem()->getId():null);
                    $tmp["order"]       = 0;
                    $tmp["color"]       = "#".($bookmark->getColor()?$bookmark->getColor():$this->get('session')->get('color')["main"]);
                    $tmp["icon"]        = $weburl.($bookmark->getIcon()?$bookmark->getIcon()->getLabel():"uploads/icon/icon_pin.png");

                    array_push($output["bookmarks"],$tmp);
                }
            }
        }

        if($only==""||in_array("items",$only)) {
            if($items) {
                foreach($items as $item) {
                    $tmp=[];
                    $tmp["id"]          = $item->getId();
                    $tmp["title"]       = $item->getTitle();
                    $tmp["url"]         = $item->getUrl();
                    $tmp["target"]      = $item->getTarget();
                    $tmp["order"]       = $item->getRoworder();
                    $tmp["color"]       = "#".($item->getColor()?$item->getColor():$this->get('session')->get('color')["main"]);
                    $tmp["icon"]        = $weburl.($item->getIcon()?$item->getIcon()->getLabel():"uploads/icon/icon_pin.png");
                    $tmp["essential"]   = $item->getEssential();
                    $tmp["category"]    = $item->getItemcategory()->getId();

                    array_push($output["items"],$tmp);
                }
            }

            if($itemcategorys) {
                foreach($itemcategorys as $itemcategory) {
                    $tmp=[];
                    $tmp["id"]          = $itemcategory->getId();
                    $tmp["title"]       = $itemcategory->getLabel();
                    $tmp["order"]       = $itemcategory->getRoworder();
                    $tmp["color"]       = "#".($itemcategory->getColor()?$itemcategory->getColor():$this->get('session')->get('color')["main"]);

                    array_push($output["itemcategorys"],$tmp);
                }
            }
        }

        if($only==""||in_array("groups",$only)) {
            foreach($user->getGroups() as $usergroup) {
                $tmp=[];
                $tmp["id"]          = $usergroup->getGroup()->getId();
                $tmp["title"]       = $usergroup->getGroup()->getLabel();

                array_push($output["groups"],$tmp);
            }
        }

        if($only==""||in_array("alerts",$only)) {
            $alerts=$em->getRepository("CadolesPortalBundle:Alert")->getUserAlerts($user,null,null,$ssoitems);
            foreach($alerts as $alert) {
                $tmp=[];
                $tmp["id"]          = $alert->getId();
                $tmp["title"]       = $alert->getTitle();
                $tmp["order"]       = $alert->getRoworder();
                $tmp["category"]    = $alert->getAlertcategory()->getId();
                $tmp["description"] = $alert->getContent();
                $tmp["fghideable"]  = $alert->getFghideable();

                array_push($output["alerts"],$tmp);
            }

            $alertcategorys=$em->getRepository("CadolesPortalBundle:Alertcategory")->findAll();
            foreach($alertcategorys as $alertcategory) {
                $tmp=[];
                $tmp["id"]          = $alertcategory->getId();
                $tmp["title"]       = $alertcategory->getLabel();
                $tmp["color"]       = "#".($alertcategory->getColor()?$alertcategory->getColor():$this->get('session')->get('color')["main"]);
                $tmp["icon"]        = $weburl.($alertcategory->getIcon()?$alertcategory->getIcon()->getLabel():"uploads/icon/icon_pin.png");

                array_push($output["alertcategorys"],$tmp);
            }
        }

        if($only==""||in_array("calendars",$only)) {

            $events=$em->getRepository("CadolesPortalBundle:Calendarevent")->getUserCalendarevents($user,$this->get('session')->get('color')["main"],null,null,$firstcalendar);
            foreach($events as $event) {
                $tmp=[];
                $tmp["id"]          = $event["id"];
                $tmp["title"]       = $event["title"];
                $tmp["description"] = $event["description"];
                $tmp['start']       = $event["start"];
                $tmp['end']         = $event["end"];
                $tmp['allday']      = $event["allDay"];
                $tmp['calendar']    = $event["calendar"];

                array_push($output["calendarevents"],$tmp);

                $tmp=[];
                $tmp["id"]          = $event["calendar"];
                $tmp["title"]       = $event["name"];
                $tmp["color"]       = $event["color"];

                if(!in_array($tmp,$output["calendars"]))
                    array_push($output["calendars"],$tmp);
            }
        }



        
        // Retour
        return new Response(json_encode($output), 200);
    }    

    // rest/users
    // Liste l'ensemble des utilisateurs de ninegate et retourne ses attributs
    // key = parametre obligatoire
    // key = clé d'accès de l'api
    public function usersAction(Request $request)
    {
        $key=$request->get('key');

        // Vérification de la clé
        $realkey = $this->getParameter("apikeyninegate");
        if($key!=$realkey) {
            $output["error"]="error key";
            return new Response(json_encode($output), 400);
        }

        $weburl="https://".$this->getParameter("weburl")."/".$this->getParameter("alias")."/";

        $em = $this->getDoctrine()->getManager();
        $output = [];

        $users=$em->getRepository('CadolesCoreBundle:User')->findAll();

        foreach($users as $user) {
            // Construction de la réponse
            $output[$user->getId()]["id"]          = $user->getId();
            $output[$user->getId()]["username"]    = $user->getUsername();
            $output[$user->getId()]["firstname"]   = $user->getFirstname();
            $output[$user->getId()]["lastname"]    = $user->getLastname();
            $output[$user->getId()]["email"]       = $user->getEmail();
            $output[$user->getId()]["avatar"]      = $weburl."uploads/avatar/".$user->getAvatar();
            $output[$user->getId()]["role"]        = $user->getRole();
        }

        // Retour
        return new Response(json_encode($output), 200);
    }

    // rest/groups
    // Liste l'ensemble des groupes de ninegate et retourne ses attributs ainsi que les membres des groupes en question
    // key = parametre obligatoire
    // key = clé d'accès de l'api
    public function groupsAction(Request $request)
    {
        $key=$request->get('key');

        // Vérification de la clé
        $realkey = $this->getParameter("apikeyninegate");
        if($key!=$realkey) {
            $output["error"]="error key";
            return new Response(json_encode($output), 400);
        }

        $em = $this->getDoctrine()->getManager();
        $output = [];

        $groups=$em->getRepository('CadolesCoreBundle:Group')->findAll();

        foreach($groups as $group) {
            // Construction de la réponse
            $output[$group->getId()]["id"]      = $group->getId();
            $output[$group->getId()]["name"]    = $group->getLabel();
            $output[$group->getId()]["users"]   = [];

            $usergroups=$group->getUsers();
            foreach($usergroups as $usergroup) {
                $user=$usergroup->getUser();
                $output[$group->getId()]["users"][$user->getId()]["id"]=$user->getId();
                $output[$group->getId()]["users"][$user->getId()]["username"]=$user->getUsername();
            }
        }

        // Retour
        return new Response(json_encode($output), 200);
    }

    // rest/bookmark/add
    // Ajout d'un item ninegate existant comme bookmark d'un utilisateur
    // key = parametre obligatoire
    // key = clé d'accès de l'api
    // login = parametre obligatoire
    // login = uid de l'utilisateur sur lequel on souhaite ajouter un bookmark
    // iditem = parametre obligatoire
    // iditem = id de l'item ninegate qui doit etre ajouté en tant que bookmark  
    public function bookmarkaddAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        
        $key=$request->get('key');
        $login=$request->get('login');
        $iditem=$request->get('iditem');
        
        // Vérification de la clé
        $realkey = $this->getParameter("apikeyninegate");
        if($key!=$realkey) {
            $output["error"]="error key";
            return new Response(json_encode($output), 400);
        }

        // Tester présence des parametres
        if(is_null($login)||is_null($iditem)) {
            $output["error"]="missing parameter : login - iditem";
            return new Response(json_encode($output), 400);
        }

        // Tester l'existance du login
        $user=$em->getRepository('CadolesCoreBundle:User')->findOneBy(["username"=>$login]);
        if(!$user) {
            $output["error"]="user not exist";
            return new Response(json_encode($output), 400);
        }        

        // Tester l'existance de l'item
        $item=$em->getRepository('CadolesPortalBundle:Item')->find($iditem);
        if(!$item) {
            $output["error"]="item not exist";
            return new Response(json_encode($output), 400);
        }    
        
        $bookmark = $em->getRepository('CadolesPortalBundle:Bookmark')->findOneBy(["user"=>$user,"item"=>$item]);
        if(!$bookmark) {
            $bookmark = new Bookmark();
            $bookmark->setTitle($item->getTitle());
            $bookmark->setSubtitle($item->getSubtitle());
            $bookmark->setUrl($item->getUrl());
            $bookmark->setIcon($item->getIcon());
            $bookmark->setColor($item->getColor());
            $bookmark->setTarget($item->getTarget());
            $bookmark->setItem($item);
            $bookmark->setUser($user);

            $em->persist($bookmark);
            $em->flush();            
        }
        $output=$bookmark->getId();        

        return new Response(json_encode($output), 200);
    }

    // rest/bookmark/del
    // Suppression  d'un bookmark
    // key = parametre obligatoire
    // key = clé d'accès de l'api
    // idbookmark = parametre obligatoire
    // idbookmark = id du bookmark à supprimer
    public function bookmarkdelAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        
        $key=$request->get('key');
        $idbookmark=$request->get('idbookmark');
        
        // Vérification de la clé
        $realkey = $this->getParameter("apikeyninegate");
        if($key!=$realkey) {
            $output["error"]="error key";
            return new Response(json_encode($output), 400);
        }

        // Tester présence des parametres
        if(is_null($idbookmark)) {
            $output["error"]="missing parameter : idbookmark";
            return new Response(json_encode($output), 400);
        }

        // Tester l'existance du bookmark
        $bookmark=$em->getRepository('CadolesPortalBundle:Bookmark')->find($idbookmark);
        if(!$bookmark) {
            $output["error"]="bookmark not exist";
            return new Response(json_encode($output), 400);
        }    
        $em->remove($bookmark);
        $em->flush();        
        
        $output=[];
        return new Response(json_encode($output), 200);
    }


    // rest/alert/hide
    // Cache une alert à un utilisateur
    // key = parametre obligatoire
    // key = clé d'accès de l'api
    // login = parametre obligatoire
    // login = uid de l'utilisateur sur lequel on souhaite ajouter un bookmark
    // idalert = parametre obligatoire
    // idalert = id de l'alert à chacher
    public function alerthideAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        
        $key=$request->get('key');
        $login=$request->get('login');
        $idalert=$request->get('idalert');
        
        // Vérification de la clé
        $realkey = $this->getParameter("apikeyninegate");
        if($key!=$realkey) {
            $output["error"]="error key";
            return new Response(json_encode($output), 400);
        }

        // Tester présence des parametres
        if(is_null($login)||is_null($idalert)) {
            $output["error"]="missing parameter : login - idalert";
            return new Response(json_encode($output), 400);
        }

        // Tester l'existance du login
        $user=$em->getRepository('CadolesCoreBundle:User')->findOneBy(["username"=>$login]);
        if(!$user) {
            $output["error"]="user not exist";
            return new Response(json_encode($output), 400);
        }        

        // Tester l'existance de l'alert
        $alert=$em->getRepository('CadolesPortalBundle:Alert')->find($idalert);
        if(!$alert) {
            $output["error"]="alert not exist";
            return new Response(json_encode($output), 400);
        }    

        // Tester que l'alert est masquable
        if(!$alert->getFghideable()) {
            $output["error"]="alert not hideable";
            return new Response(json_encode($output), 400);
        }  

        // Masquer l'alert
        if(!$alert->getReaders()->contains($user)) {
            $alert->addReader($user);
            $em->persist($alert);
            $em->flush();
        }  

        $output=[];
        return new Response(json_encode($output), 200);
    }
}


