<?php
ob_start(); //FIX for login as admin
require_once(__DIR__."/../../modules/adminUsers/models/ExternalNumber.php"); // Fix for creating Users
require_once(__DIR__."/../../modules/routingQueueMonitor/models/QueueMonitor.php"); // Fix for creating Users
class QueueMonitorTest extends CDbTestCase {
    
    private $queues = array();
    private $member = array();
    private $tiers = array();
    private $permissions = array();
    
    private function prepareTest()
    {
        $identity = new UserIdentity('admin', 'demo'); //FIXME ?
        $identity->authenticate();
        Yii::app()->user->login($identity);
        $this->assertFalse(app()->user->isGuest);
        
        $this->createTestQueues();
        $this->createTestMember();
        $this->createTestTiers();
        $this->createTestPermissions();
        
    }
    
    private function createTestQueues()
    {
        for ($i=1;$i<5;$i++) {
            
            $attributes = array(
                "extension"=>"1235123".$i,
                "name"=>"QueueMonitorTest".$i,
            );
            $queue = Queue::model()->findAllByAttributes($attributes);
            if (count($queue)) {
                $queue[0]->delete();
            }
            $newQueue = new Queue();
            $newQueue->attributes = $attributes;
            if (!$newQueue->save()) {
                print_r($newQueue->errors);
            } else {
                $this->queues[] = $newQueue;
            }
        }
    }
    
    private function createTestMember()
    {
        for ($i=1;$i<5;$i++) {
            
            $attributes = array(
                "extension"=>"12124".$i,
                "name"=>"queuemonitormember".$i,
                "firstname" => "TestUser".$i,
                "lastname" => "MonitorQueue".$i,
                "pin"=>"1234",
                "group" => Groups::model()->findAllByAttributes(array("type"=>"allUsers"))[0]->id,
                "isSystemAdmin"=>"0"
            );
            $this->deleteOldUsers($attributes);
            
            $user = new User();
            $user->attributes = $attributes;
            if (!$user->save()) {
                print_r($user->errors);
            } else {
                $this->member[] = $user;
            }
        }
    }
    
    private function deleteOldUsers($attributes)
    {
        $user = User::model()->findAllByAttributes($attributes);
        if (count($user)) {
            $user[0]->delete();
        }
    }
    
    private function createTestTiers()
    {
        $this->removeOldTiers();
        
        foreach ($this->queues as $queue) {
            foreach ($this->member as $member) {
                
                $attributes = array(
                    "userId"=>$member->id,
                    "queueId" => $queue->id,
                    "type"=>"0",
                );
                
                $tier = new Tiers();
                $tier->attributes = $attributes;
                if (!$tier->save()) {
                    print_r($tier->errors);
                } else {
                    $this->tiers[] = $tier;
                }
            }
        }
    }
    
    private function removeOldTiers()
    {
        foreach ($this->queues as $queue) {
            $tiers = Tiers::model()->findAll(array("queueId"=>$queueId));
            foreach ($tiers as $tier) {
                $tier->delete();
            }
        }
    }
    
    private function createTestPermissions()
    {
        $this->deleteOldPermissions();
        foreach ($this->queues as $queue) {
            
            $attributes = array(
                "groupId" => Groups::model()->findAllByAttributes(array("type"=>"allUsers"))[0]->id,
                "type" => "monitorQueues",
                "itemId" => $queue->id
            );

            $permission = new Permissions();
            $permission-> attributes = $attributes;
            
            if (!$permission->save()) {
                print_r($permission->errors);
            } else {
                $this->permissions[] = $permission;
            }
        }
        date_default_timezone_set("UTC"); // fix for system time
        $permission->createPermissionsFile();
    }
    
    private function deleteOldPermissions()
    {
        foreach ($this->queues as $queue) {
            $permissions = Permissions::model()->findAll(array('itemId'=>$queue->id));
            foreach ($permissions as $permission) {
                $permission->delete();
            }
        }
    }
    
    public function testConstructor()
    {
        $this->prepareTest();
        
        foreach ($this->queues as $queue) {
            $queueMonitor = new QueueMonitor($queue->id);
            $this->assertTrue($queueMonitor->getQueue() instanceof Queue);
            $this->assertTrue(count($queueMonitor->getMember()) == 4);
            $this->assertTrue(count($queueMonitor->getCurrentLoggendInAgents()) == 0);
        }
    }
    
    public function testGetDataProvider()
    {
        $this->prepareTest();
        
        $queueMonitor = new QueueMonitor($this->queues[0]->id);
        $dataProvider = $queueMonitor->getDataprovider();
        $this->assertTrue($dataProvider instanceof CArrayDataProvider, "Dataprovider is not a instance of CArrayDataProvider!");
        $this->assertTrue($dataProvider->totalItemCount == 5, "failed on total itemcount");
        
        $data = $dataProvider->data;
       
        //check DynamicGrid Prototype Item
        $this->assertTrue($data[0]["id"] == 0);
        $this->assertTrue($data[0]["queueId"] == "");
        $this->assertTrue($data[0]["memberId"] == "");
        $this->assertTrue($data[0]["name"] == "");
        $this->assertTrue($data[0]["loggedIn"] == "");
        $this->assertTrue($data[0]["static_member"] == 0);
        $this->assertTrue($data[0]["status"] == "");
        $this->assertTrue($data[0]["jabberStateColor"] == "gray");
        $this->assertTrue($data[0]["phoneStateColor"] == "gray");
        
    }
    
    public function testGetAvailableUsers()
    {    
        $this->prepareTest();
        
        foreach ($this->tiers as $tier) {
            if ($tier->userId == $this->member[0]->id || $tier->userId == $this->member[1]->id) {
                $tier->delete();
            }
        }
        
        $queueMonitor = new QueueMonitor($this->queues[0]->id);
        $availabeUsers = $queueMonitor->getAvailableUsers();
        $this->assertTrue(is_array($availabeUsers));
        $this->assertTrue(count($availabeUsers) == 3);
    }
    
    public function testGetCurrentLoggedAgents()
    {
        $this->prepareTest();
        $this->loginAgentsFromQueue(0);
        $this->logoutAgentsFromQueue(1);
        
        $queueMonitor = new QueueMonitor($this->queues[0]->id);
        $loggedInAgents = $queueMonitor->getCurrentLoggendInAgents();
        $this->assertTrue(count($loggedInAgents) == 4);
        
        $queueMonitor = new QueueMonitor($this->queues[1]->id);
        $loggedInAgents = $queueMonitor->getCurrentLoggendInAgents();
        $this->assertTrue(count($loggedInAgents) == 0);
    }
    
    private function loginAgentsFromQueue($index)
    {
        foreach ($this->tiers as $tier) {
            if ($tier->queueId == $this->queues[$index]->id) {
                $tier->loggedIn = 1; 
                
            }
            $tier->save();
        }
    }
    
    private function logoutAgentsFromQueue($index)
    {
        foreach ($this->tiers as $tier) {
            if ($tier->queueId == $this->queues[$index]->id) {
                $tier->loggedIn = 0; 
                
            }
            $tier->save();
        }
    }
    
    public function testGetGeneralQueueInfoDataProvider()
    {
        $this->prepareTest();
        $this->loginAgentsFromQueue(0);
        $queueMonitor = new QueueMonitor($this->queues[0]->id);
        $dataProvider = $queueMonitor->getGeneralQueueInfoDataProvider();
        
        $this->assertTrue($dataProvider instanceof CArrayDataProvider);
        $this->assertTrue($dataProvider->totalItemCount == 5);
        
        $data = $dataProvider->data;
        foreach ($data as $key => $item) {
            $this->assertTrue($key == $item["id"]);
            $this->assertTrue(count($item) == 3);
        } 
        /* // FIXME 
        $this->assertTrue($data[0]["value"]=="BLUBB");
        $this->assertTrue($data[0]["name"]=="Current Calls");
        $this->assertTrue($data[1]["value"]=="BLUBB");
        $this->assertTrue($data[1]["name"]=="Waiting Calls");
        $this->assertTrue($data[2]["value"]== 4);
        $this->assertTrue($data[2]["name"]=="Current Agents");
        $this->assertTrue($data[3]["value"]== 4);
        $this->assertTrue($data[3]["name"]=="Logged-In Agents");
        $this->assertTrue($data[4]["value"]=="blubb");
        $this->assertTrue($data[4]["name"]=="Free Agents");
        */
        $this->logoutAgentsFromQueue(1);
        $queueMonitor = new QueueMonitor($this->queues[1]->id);
        $dataProvider = $queueMonitor->getGeneralQueueInfoDataProvider();
        
        $this->assertTrue($dataProvider instanceof CArrayDataProvider);
        $this->assertTrue($dataProvider->totalItemCount == 5);
        
        $data = $dataProvider->data;
        foreach ($data as $key => $item) {
            $this->assertTrue($key == $item["id"]);
            $this->assertTrue(count($item) == 3);
        } 
    }
}