<?php

class DefaultController extends Controller
{
    // Disable custom layout
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules()
    {
        return array(
            array('allow',
                'actions' => array(
                    "index",
                ),
//                'expression' => (AccessManager::checkSessionPermission($this->module->id) == "true" && $this->getCurrentQueueId(User::getCurrentRealUser()) != null) ? "true" : "false",
                'expression' => AccessManager::checkSessionPermission($this->module->id),
            ),
            array('deny',
                "actions"=>array(
                    'queueOverview',
                    'toggleAgentLoginState',
                    'addAgent',
                    'removeAgent',
                    'updateTier',
                    'getJSONCallInfo',
                    "getJSONAgentInfo"
                ),
                'users' => array('*'),
            ),
            array('deny',
                'users' => array('*'),
            )
        );
    }
    
    public function actionIndex() {

        $user = User::model()->getCurrentRealUser();
        $queueId = $this->getCurrentQueueId($user);

        if ($this->userHasPermissions($queueId, $user)) {
            $agentDataProvider = $this->getAllAgentsDataprovider();
            $callDataProvider = $this->getAllCallDataprovider();
            $queueIds = $this->getQueueIds();
            $toggleAgentLoginPermissions = $this->getToggleAgentLoginPermissions($user);
            $transferCallToPermissions = $this->getAgetIDsForModeratorPermissions($user);
            $transferCallFromPermissions = $this->getTransferCallFromPermissions($user);
            $this->render(
                    "index", array(
                    "queueIds" => json_encode($queueIds),
                    "agentDataProvider" => $agentDataProvider,
                    "callDataProvider" => $callDataProvider,
                    "toggleAgentLoginPermissions" => $toggleAgentLoginPermissions,
                    "transferCallToPermissions" => $transferCallToPermissions,
                    "transferCallFromPermissions" => $transferCallFromPermissions
                )
            );
        } else {
            $this->render(
                "setQueueMonitorPermissionsGuide"
            );
        }
    }

    private function getAllAgentsDataprovider()
    {
        $agentPrototype[] = array(
            "id" => 0,
            "state"=>"",
            "agent_extension" => "",
            "agent_firstname" => "",
            "agent_lastname" => "",
            "extension" => "",
            "id" => "",
            "loggedIn" => "",
            "name" => "",
            "queueId" => "",
            "static_member" => "",
            "userId" => "",
        );
        return new CArrayDataProvider($agentPrototype);    
    }
    
    private function getQueueIds() {
        $queueIds = array();
        $user = User::getCurrentRealUser();
        if ($user) {
            $permission = new Permissions();
            $queueMonitorPermissions = $permission->getPermissionsArray($attributes = array("type"=>"monitorQueues", "groupId"=>$user->group), true);
            foreach ($queueMonitorPermissions as $queueMonitorPermission) {
                 $queueIds[] = $queueMonitorPermission["itemId"];
            }
        }
        return $queueIds;
    }
    
    private function getAllCallDataprovider()
    {
        $callPrototype[] = array(
            "id"=>0,
            "agent"=> "",
            "callid"=>"",
            "direction"=> "",
            "from_external"=> "",
            "owner_id"=> "",
            "queue_extension"=>"",
            "remote_number"=> "",
            "state"=> "",
            "timestamp"=> "",
            "typ"=> ""
        );
        return new CArrayDataProvider($callPrototype);
    }
    
    public function actionQueueOverview($queue_id=null)
    {
        $user = User::model()->getCurrentRealUser();
        $queueId = $this->getCurrentQueueId($user, $queue_id);
        
        if ($this->userHasPermissions($queueId, $user)) {
            $queueMonitor = new QueueMonitor($queueId);

            $navbarQueueDropdown = $queueMonitor->getQueuesForNavbar($user);

            $this->render('queueOverview', array(
                "queueMonitor" => $queueMonitor,
                "navbarQueueDropdown"=>$navbarQueueDropdown
            ));
        } else {
            throw new CHttpException(403, Yii::t('yii','You are not authorized to perform this action.'));
        }
    }

    private function getCurrentQueueId($user, $queueId=null)
    {
        if (isset($queueId)) {
            return $queueId;
        } else {
            $permissions = $this->getQueueMonitorPermissinonsForUser($user);
            
            if (count($permissions)) {
               return $this->getFirstItemIdFromPermissions($permissions);
            }
        }
        return null;
    }
    
    private function getQueueMonitorPermissinonsForUser($user)
    {
        $permissions = Permissions::model()->getPermissionsArray(
                array(
                    'type' => "monitorQueues",
                    'groupId' => $user->group,
                ), true
        );
        return $permissions;
    }
    
    private function getFirstItemIdFromPermissions($permissions)
    {
        foreach ($permissions as $permission) {
            return $permission["itemId"];
        }
    }
    
    private function userHasPermissions($queueId, $user)
    {    
        $permissions = $this->getQueueMonitorPermissinonsForUser($user);
        
        foreach ($permissions as $permission) {
            
            if ($permission["itemId"] == $queueId) {
                return true;
            }
        }
        return false;
    }
    
    private  function getToggleAgentLoginPermissions($user)
    {
        $permissions = Permissions::model()->getPermissionsArray(
                array(
                    'type' => "toggleAgentLogin",
                    'groupId' => $user->group,
                ), true
        );
        
        $allowedTierIds = array();
        foreach ($permissions as $permissionId => $permission) {
            $tiers = Tiers::model()->find(array("queueId" => $permission["itemId"]), "id");
            foreach ($tiers as $tier) {
                $allowedTierIds[] = $tier->id;
            }
        }
        
        return $allowedTierIds;
    }
    
    private function getAgetIDsForModeratorPermissions($user)
    {   
        $permissions = Permissions::model()->getPermissionsArray(
                array(
                    'type' => "moderator",
                    'groupId' => $user->group,
                ), true
        );
        
        $allowedTierIds = array();
        foreach ($permissions as $permissionId => $permission) {
            $tiers = Tiers::model()->find(array("queueId" => $permission["itemId"]), "id");
            foreach ($tiers as $tier) {
                $allowedTierIds[] = $tier->id;
            }
        }
        
        return $allowedTierIds;
    }
    
    private function getTransferCallFromPermissions($user)
    {
        $permissions = Permissions::model()->getPermissionsArray(
                array(
                    'type' => "moderator",
                    'groupId' => $user->group,
                ), true
        );
        
        $allowedQueueExtensions = array();
        foreach ($permissions as $permissionId => $permission) {
            $queue = Queue::model()->findByPk($permission["itemId"]);
            $allowedQueueExtensions[] = $queue->extension;
        }
        
        return $allowedQueueExtensions;
    }
    
    public function actiontoggleAgentLoginState()
    {
        $tier = $this->getTier($_POST["memberId"], $_POST["queueId"]);

        if (!$tier->static_member) {
            if ($tier->loggedIn == '0' || $tier->loggedIn == null) {
                $tier->loggedIn = 1;
                $label = __('PHONESETTINGS_MY_PHONES_LOGOUT_BUTTON');
            } else {
                $tier->loggedIn = 0;
                $label = __('PHONESETTINGS_MY_PHONES_LOGIN_BUTTON');
            }
            if ($tier->save()) {
                echo json_encode(array("loggedIn"=>$tier->loggedIn,"label"=>$label));
            }
        }
    }
    
    public function actionAddAgent()
    {
        $tier = new Tiers();        
        $this->setTierDefaultParameter($tier);
        
        if (!count($tier->find($tier->attributes,"id"))) {
            if ($tier->save()) {
                $response = array(filter_input(INPUT_POST,"label"));
                echo json_encode($response);
            } else {
                print_r($tier->errors);
                die();
            }
        }
    }
    
    private function setTierDefaultParameter(&$tier)
    {
        $userId = filter_input(INPUT_POST,"userId");
        $queueId = filter_input(INPUT_POST,"queueId");
        $user = User::model()->findByPk($userId);
        $tierType = TiersType::user;
        $static_member = 0;
        if (!$user) {
            $user = ExternalAgent::model()->findByPk($userId);
            $tierType = TiersType::external;
            $static_member = 1;
        }
        
        $tier->attributes = array(
            "userId"=>$user->id,
            "queueId"=>$queueId,
            "level"=>"",
            "position"=>"1",
            "type"=>$tierType,
            "static_member"=>$static_member,
            "loggedIn"=>"0",
            "timeout"=>"",
        );
    }
    
    public function actionRemoveAgent()
    {    
        $tier = $this->getTier($_POST["agentId"], $_POST["queueId"]);
        echo json_encode(array("deleted"=>$tier->delete()));
    }
    
    private function getTier($agentId, $queueId)
    {
        $tiers = Tiers::model()->find(array("userId"=>$agentId, "queueId"=>$queueId),"id");
        $tier = $tiers[0];
        return $tier;
    }
    
    public function actionUpdateTier()
    {
        if (isset($_POST["Tiers"])) {
            
            $tiers = $_POST["Tiers"];
            $tier = Tiers::model()->findByPk($tiers["id"]);
            $this->performAjaxValidation($tier);
            unset($tiers["id"]);
            $tier->attributes = $tiers;
            if ($tier->static_member) {
                $tier->loggedIn = 1;
            }
            $tier->save();
            Yii::app()->end();
        }
        $userId = filter_input(INPUT_POST, "userId");
        $queueId = filter_input(INPUT_POST,"queueId");
        $tier = $this->getTier($userId, $queueId);
        $this->renderPartial("updateTierForm",array("tier"=>$tier),false,true);
    }
    
    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='update-tier-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
    
    public function renderUserDropDown($queueMonitor)
    {
        $availableUsers = $queueMonitor->getAvailableUsers();
        return $this->renderPartial('queueMonitoeUserDropdown',array("availableUsers" => $availableUsers, "queueMonitor" => $queueMonitor),true,false);
    }
    
    public function renderMemberNameCell($data, $row, $column)
    {
        return $this->renderPartial('memberNameCell',array("formattedName" => $data["name"],"memberId"=>$data["memberId"], "row"=>$row, "column"=>$column),true,false);
    }
    
    public function renderToggleLoginButton($data)
    {
        return $this->renderPartial("toggleLoginButton",array("data"=>$data),true,false);
    }
    
    public function renderAgentStatus($data) {
        return $this->renderPartial("agentStatusCell",array("data"=>$data),true,false);
    }
    
    public function renderCallStatus($data) {
        return $this->renderPartial("callStatusCell",array("data"=>$data),true,false);
    }
    
    public function renderAgentLoginButtonPrototype()
    {
        $this->renderPartial("agentLoginButtonPrototype");
    }
}