<?php

namespace Plugins\VotePlugin;

use Core\View\View;
use Core\View\ElementView;
use Plugins\VotePlugin\Entity\VoteVote;
use Core\Core\Response;

class VotePlugin {

    public $Author = 'Webemyos';
    public $Version = '1.0.0.0';

    function __construct($core) {
        $this->Core = $core;
    }

    function GetType() {
        return "Vote";
    }

    /*     * *
     * Render the plugin
     */

    function Render($entityName, $entityId) {

        $view = new View(__DIR__ . "/View/index.tpl", $this->Core);
        $view->AddElement(new ElementView("EntityName", $entityName));
        $view->AddElement(new ElementView("EntityId", $entityId));

        $stat = self::GetStat($entityName, $entityId);
        $view->AddElement(new ElementView("plus", $stat["plus"]));
        $view->AddElement(new ElementView("minus", $stat["minus"]));

        return $view->Render();
    }

    /*     * *
     * Render the Js in the VotePlugin
     */

    function GetRegisterPlugin() {
        return '<script>document.addEventListener("DOMContentLoaded", function() {  
                Plugin.Register("VotePlugin", "VotePlugin"); }) ;</script>';
    }

    /*     * *
     * Vote on entity
     * Return number on Positive 
     */

    function Vote($params) {

        if (!$this->Core->IsConnected()) {
            return Response::Error(array("Message" => "NotConnect"));
        }

        $VoteVote = new VoteVote($this->Core);
        $userVote = $VoteVote->Find("UserId= " . $this->Core->User->IdEntite . " and EntityName = '" . $params->EntityName . "' and EntityId=" . $params->EntityId);

        if (count($userVote) > 0) {
            $VoteVote = $userVote[0];
        } else {
            $VoteVote = new VoteVote($this->Core);
            $VoteVote->UserId->Value = $this->Core->User->IdEntite;
            $VoteVote->EntityName->Value = $params->EntityName;
            $VoteVote->EntityId->Value = $params->EntityId;
        }

        $VoteVote->Vote->Value = $params->Vote;
        $VoteVote->Save();

        return Response::Success(self::GetStat($params->EntityName, $params->EntityId));
    }

    /*     * *
     * Get State on a entity
     */

    function GetStat($entityName, $entityId) {

        $request = "select Vote from VoteVote Where EntityName ='" . $entityName . "' and EntityId=" . $entityId;
        $result = $this->Core->Db->GetArray($request);

        $plus = 0;
        $minus = 0;

        foreach ($result as $res) {

            if ($res["Vote"] > 0) {
                $plus++;
            } else {
                $minus++;
            }
        }

        return array("plus" => $plus, "minus" => $minus);
    }
}
