<?php

class QueueMonitor {
    
    private $queue = null;
    private $member = array();
    private $currentLoggendInAgents = array();
    
    public function getMember()
    {
        return $this->member;
    }
    public function getQueue()
    {
        return $this->queue;
    }
    
    public function getCurrentLoggendInAgents()
    {
        return $this->currentLoggendInAgents;
    }
    
    public function __construct($queueId)
    {
        $this->queue = Queue::model()->findByPk($queueId);
        if ($this->queue) {
            $this->member = array_merge($this->queue->queueMembers,$this->queue->externalAgents);
            $this->setCurrentLoggedInAgents();
        }
    }
    
    private function setCurrentLoggedInAgents()
    {
        $tiers = Tiers::model()->find(array("queueId"=>$this->queue->id),"id");
        $loggedInAgents = array();
        foreach ($this->member as $member) {
            foreach ($tiers as $tier) {
                if ( $tier->userId == $member->id) {
                    
                    if (($tier->loggedIn == 1) || ($tier->static_member == 1)) {
                        $loggedInAgents[] = $member;
                    } 
                }
            }
        }
        $this->currentLoggendInAgents = $loggedInAgents;
    }

    public function getGeneralQueueInfoDataProvider()
    {
        $dataDefaults = array(
            "CALLS"             => "<p class = 'label label-info queue-monitor-currentCalls'>0</p>",
            "_WAITING_CALLS"    => "<p class = 'label label-warning queue-monitor-currentPendingCalls'>0</p>",
            "AGENTS"           => "<p class = 'label label-info queue-monitor-currentAgents'>".(count($this->queue->queueMembers)+count($this->queue->externalAgents))."</p>",
            "LOGGEDIN_AGENTS"   => "<p class = 'label label-success' queue-monitor-loggedInAgents>".count($this->currentLoggendInAgents)."</p>",
            "FREE_AGENTS"       => "<p class = 'label label-success queue-monitor-freeAgents'>0</p>"
        );
        $i = 0;
        $data = array();
        
        foreach ($dataDefaults as $key => $value) {
            $data[] = array(
                "id"    => $i++,
                "name"  => __("ROUTING_QUEUE_MONITOR_GENERAL_QUEUE_INFO_CURRENT_".$key),
                "value" => $value
            );
        }
        return new CArrayDataProvider($data);
    }

    public function getDataprovider()
    {
        $members = array_merge($this->queue->getQueueMembers(),$this->queue->getExternalAgents());
        
        $data = $this->getDataForDataprovider($members);
        
        $dataProvider=new CArrayDataProvider($data,
            array('pagination' => array(
                    'pageSize' => false
                )
            )
        );
        
        $dataProvider->sort = $this->getCustomSort();
        return $dataProvider;
    }
    
    private function getDataForDataprovider($members)
    {
        
        $data = array();
        $i = 0;
        
        $data[]= $this->getPrototypeData($i);
        foreach ($members as $member) {
            $tier = Tiers::model()->find(array("queueId"=>$this->queue->id, "userId"=>$member->id),"queueId");
            if ($tier[0]->type == TiersType::user) {
                $data[] = $this->getInternalAgentData($tier, $member,$i);
            } else {
                $data[] = $this->getExternalAgentData($tier, $member,$i);
            }
        }
        return $data;
    }
    
    private function getPrototypeData(&$i)
    {
        return array(
            "id"=>$i++,
            "queueId" =>'',
            "memberId" => "",
            "name" =>'',
            "loggedIn" => "",
            "static_member"=>0,
            "status" => "",
            "jabberStateColor"=>"gray",
            "phoneStateColor"=>"gray",
        );
    }
    
    private function getInternalAgentData($tier, $member, &$i)
    {
        return array(
            "id"=>$i++,
            "queueId" =>$tier[0]->queueId,
            "memberId" => $member->id,
            "jabberStateColor" => $member->jabberStateColor,
            "phoneStateColor"=> $member->stateColor,
            "name" =>'<'.$member->extension.'> '.getFormatedNameForSudoBar($member),
            "loggedIn" => $tier[0]->loggedIn == '0' || $tier[0]->loggedIn == '' ? 0 : 1,
            "static_member"=>$tier[0]->static_member,
            "status" => "" //FIXME
        );
    }
    
    private function getExternalAgentData($tier, $member, &$i)
    {
        return array(
            "id"=>$i++,
            "queueId" =>$tier[0]->queueId,
            "memberId" => $member->id,
            "name" =>'<'.$member->number.'> '.$member->name,
            "loggedIn" => $tier[0]->loggedIn == '0' || $tier[0]->loggedIn == '' ? 0 : 1,
            "static_member"=>$tier[0]->static_member,
            "status" => "" //FIXME
        );
    }
    
    private function getCustomSort()
    {
        $sort = new CSort();
        $sort->attributes = array(
            'name'=>array(
                'asc'=>'name DESC',
                'desc'=>'name ASC',
            ),
            'loggedIn'=>array(
                'asc'=>'loggedIn DESC',
                'desc'=>'loggedIn ASC',
            ),
           
        );
        $sort->defaultOrder='name ASC';
        return $sort;
    }
        
    public function getQueuesForNavbar($user)
    {
        $navbarDropdownItem = array(
                'label'=>"<".$this->queue->extension."> ".$this->queue->name,
                'url'=>'#',
                'items'=> $this->getItemsForNavbar($user),
                'data-translation-id'=>'QUEUEMONITOR_NAVBAR_GATEWAY_DROPDOWN_LABLE',
        );
        
        return $navbarDropdownItem;
    }
    
    private function getItemsForNavbar($user)
    {
        $permissions = $this->getUserGroupPermissionsForQueue($user);
        $items = array();
        foreach ($permissions as $permission) {
            $queue = Queue::model()->findByPk($permission['itemId']);
            $queueId = filter_input(INPUT_GET, "queue_id");
            $active = false;
            if (isset($queueId) &&  $queueId == $queue->id) {
                $active = true;
            }
            $items[] = array(
                'label' => $queue->name,
                'url' => 'index.php?r=routingQueueMonitor/default/queueOverview&queue_id=' . $queue->id,
                'active' => $active
            );
        }
        return $items;
    }
    
    private function getUserGroupPermissionsForQueue($user)
    {
        $permissions = Permissions::model()->getPermissionsArray(
            array(
                'type' => "monitorQueues",
                'groupId' => $user->group,
            ), true
        );
        return $permissions;
    }
    
    public function getAvailableUsers() {
        $availableUsers = array();
        
        $allUsers = User::model()->findAll();
        
        foreach ($allUsers as $key => $user) {
            foreach ($this->member as $member) {
                if ($user->id == $member->id) {
                    unset($allUsers[$key]);
                }
            }
        }
        
        foreach ($allUsers as $user) {
            $availableUsers[] = array(
                "userId" => $user->id,
                "formattedName" => '<'.$user->extension.'> '.getFormatedNameForSudoBar($user),
            );
        }
        return $availableUsers;
    }
    
    public function getAvailableExternalAgents() {
        $availableAgents = array();
        $availableExternalAgents = ExternalAgent::model()->findAll();
  
        foreach ($availableExternalAgents as $key => $user) {
            foreach ($this->member as $member) {
                if ($user->id == $member->id) {
                    unset($availableExternalAgents[$key]);
                }
            }
        }
        
        foreach ($availableExternalAgents as $agent) {
            $availableAgents[] = array(
                "userId" => $agent->id,
                "formattedName" => '<'.$agent->number.'> '.$agent->name
            );
        }
        return $availableAgents;
    }
}