 <?php

class AdminQueueMonitorTest extends WebTestCase {

    
    public function testDynamicGrid()
    {
        $gridviewXPath = '//*[@id="QueueMonitor-grid"]';
        $this->removeAllTiers();
        $this->goToModulePage();
        $this->assertTrue($this->getXpathCount("//table") == 2);
        $this->assertElementContainsText($generalDataGridXPath."//tr[3]/td[last()]", "0");
        $this->addAllUsersToQueue();
        $this->removeAllUsersFromQueue();
    }
    
    private function removeAllTiers()
    {
        $tiers = Tiers::model()->find(array(),"id");
        foreach ($tiers as $tier) {
            $tier->delete();
        } 
    }
    
    private function goToModulePage()
    {
        app()->language = "de_de";
        $this->open('?r=routingQueueMonitor');
        $this->assertElementPresent('name=LoginForm[username]');
        $this->type('name=LoginForm[username]', 'admin');
        $this->type('name=LoginForm[password]', 'demo');
        $this->clickAndWait("//input[@value='Login']");
    }
    
    
    
    private function addAllUsersToQueue()
    {
        $gridviewXPath = '//*[@id="QueueMonitor-grid"]';
        $generalDataGridXPath = "//*[@id='Queue-general-data-grid']";
        
        while ($this->getXpathCount('//select[contains(@id,"userDropdown")]//option') >0) {
            $this->addAgent();
        }
        
        $this->assertTrue($this->getXpathCount('//select[contains(@id,"userDropdown")]//option') == 0);
        
        $this->waitForCondition("var onlineAgents = selenium.getText('//*[@id=\'Queue-general-data-grid\']/table/tbody/tr[4]/td[2]'); onlineAgents == '5'",10000);
        $this->assertElementContainsText($generalDataGridXPath."//tr[3]/td[last()]/p", "5");
        $this->assertElementContainsText($generalDataGridXPath."//tr[4]/td[last()]/p", "5");
        $this->assertNotVisible($gridviewXPath."//tfoot");
    }

    private function addAgent()
    {
        
        $gridviewXPath = '//*[@id="QueueMonitor-grid"]';
        $buttonId = "memberId_".$this->getValue($gridviewXPath."//select");
        
        $scriptWaitForNotLoadingGrid = "var elementClass = selenium.browserbot.getCurrentWindow().document.getElementById('QueueMonitor-grid').className; elementClass == 'grid-view'";
        $scriptWaitForLoadingGrid = "var elementClass = selenium.browserbot.getCurrentWindow().document.getElementById('QueueMonitor-grid').className; elementClass == 'grid-view grid-view-loading'";
        
        $this->waitForCondition($scriptWaitForNotLoadingGrid, 10000);
        $this->click('//*[@id="QueueMonitor-grid"]//tfoot//div[last()]');
        $this->waitForCondition($scriptWaitForLoadingGrid, 10000);
        $this->waitForCondition($scriptWaitForNotLoadingGrid, 10000);
        
        $scriptWaitForLoginButton = "var elementClass = selenium.browserbot.getCurrentWindow().document.getElementById('".$buttonId."'); elementClass != null";
        $this->waitForCondition($scriptWaitForLoginButton, 10000);

        $this->click('//*[@id="'.$buttonId.'"]');
    }
    
    private function removeAllUsersFromQueue()
    {
        $gridviewXPath = '//*[@id="QueueMonitor-grid"]';
        
        while ($this->getXpathCount($gridviewXPath."//*[@class='icon-trash']") > 1) {
            $this->removeLastAgentInGrid();
        }
        $this->assertTrue($this->getXpathCount('//select[contains(@id,"userDropdown")]//option') == 5);
        $this->assertVisible($gridviewXPath."//tfoot");
    }
    
    private function removeLastAgentInGrid()
    {
        $this->click('//*[@id="QueueMonitor-grid"]//tbody/tr[last()]/td[last()]//a[@class="delete"]');
        sleep(1); // wait for Ajax response
    }

    public function testQueueDropdown() {
        $this->goToModulePage();
        $this->assertTextPresent("<12351231> QueueMonitorTest1 ");
        $this->click('//*[@id="yw0"]/li[2]/a');
        $this->clickAndWait("//a[text() = 'QueueMonitorTest2']");
        $this->assertTextPresent("<12351232> QueueMonitorTest2 ");
        $this->click('//*[@id="yw0"]/li[2]/a');
        $this->assertElementContainsText("//*[@id='yw0']//li[@class='active']/a", "QueueMonitorTest2");
    }
    
    
    public function testUpdateTierForm()
    {
        $this->goToModulePage();
        $this->assertTrue($this->getXpathCount("//table") == 2);
        $this->addAllUsersToQueue();
        $this->openUpdateForm();
        $this->checkValidation();
        $this->tierSaveViaUpdateForm();
    }
    
    private function openUpdateForm() {
        $xpathFirstUpdateButton = '//*[@id="QueueMonitor-grid"]/table/tbody/tr[2]/td[4]/a[1]';
        $this->click($xpathFirstUpdateButton);
        $scriptModalIsOpen = "var displayStyle = selenium.browserbot.getCurrentWindow().getComputedStyle(selenium.browserbot.getCurrentWindow().document.getElementById('QueueMonitor-grid_Modal')).display; displayStyle !== 'none'";
        $this->waitForCondition($scriptModalIsOpen,10000);
        $xpathModalUpdateHeader = '//*[@id="QueueMonitor-grid_Modal"]/div[1]';
        $this->assertVisible($xpathModalUpdateHeader);
    }
    
    private function checkValidation()
    {
        $userDataInputs = array();
        // add Username Field to generic validation.
        $userDataInputs[] = array(
            'selector' => "//input[@id='Tiers_position']",
            'translationKey' => 'USERS_MODEL_NAME',
            'defaultValue' => 'admin' //invalid value to check unique validator after client validation
        );

        // add Password Field to generic validation.
        $userDataInputs[] = array(
            'selector' => "//input[@id='Tiers_timeout']",
            'rules' => array('numerical' => array(
                            'integerOnly' => true,
                        ),
            ),
            'translationKey' => 'TIERS_MODEL_TIMEOUT',
            'defaultValue' => 'demo'
        );

        $this->checkInputValidation(
            $userDataInputs,
            "//button[@id='QueueMonitor-grid_Modal_saveBtn']"
        );  
    }
    
    private function tierSaveViaUpdateForm()
    {
        $this->check('//*[@id="Tiers_static_member"]');
        $this->select('//*[@id="Tiers_level"]', 9);
        $this->type('//*[@id="Tiers_position"]',9);
        $this->type('//*[@id="Tiers_timeout"]',9);
        $this->click("//button[@id='QueueMonitor-grid_Modal_saveBtn']");
        
        $scriptModalIsClosed = "var displayStyle = selenium.browserbot.getCurrentWindow().getComputedStyle(selenium.browserbot.getCurrentWindow().document.getElementById('QueueMonitor-grid_Modal')).display; displayStyle === 'none'";
        $this->waitForCondition($scriptModalIsClosed,10000);
        
        $scriptWaitForNotLoadingGrid = "var elementClass = selenium.browserbot.getCurrentWindow().document.getElementById('QueueMonitor-grid').className; elementClass == 'grid-view'";
        $this->waitForCondition($scriptWaitForNotLoadingGrid, 10000);
        $xpathLoggedInButton = '//*[@id="QueueMonitor-grid"]/table/tbody/tr[2]/td[2]/a';
        $this->assertTrue($this->getText($xpathLoggedInButton) == __("ROUTING_QUEUE_MONITOR_STATIC_MEMBER_BUTTON"));
        
        $this->openUpdateForm();

        $this->assertChecked('//*[@id="Tiers_static_member"]');
        $this->assertElementValueEquals('//*[@id="Tiers_level"]', "8");
        $this->assertElementValueEquals('//*[@id="Tiers_position"]', "9");
        $this->assertElementValueEquals('//*[@id="Tiers_timeout"]', "9");
        
        $this->uncheck('//*[@id="Tiers_static_member"]');
        $this->click("//button[@id='QueueMonitor-grid_Modal_saveBtn']");
        $this->waitForCondition($scriptModalIsClosed,10000);
        

        $this->waitForCondition($scriptWaitForNotLoadingGrid, 10000);
        $this->assertTrue($this->getText('//*[@id="QueueMonitor-grid"]/table/tbody/tr[2]/td[2]/button') == __("ROUTING_QUEUE_MONITOR_LOGOUT_BUTTON"));
    }
    
    public function testTableSortByName()
    {
        $this->removeAllTiers();
        $this->goToModulePage();
        $this->addAllUsersToQueue();
        
        
        $xpathSortByNameLink = '//*[@id="QueueMonitor-grid_c0"]/a';
        
        
        // Name ASC
        $this->click($xpathSortByNameLink);
        $tableRowCount = $this->getXpathCount('//*[@id="QueueMonitor-grid"]//tbody//tr');
        $this->assertTrue($tableRowCount == 6, "more or less then 6 table rows found");
        
        $values = array();
        for ($i = 6; $i > 1; $i--) {
            $pk = $this->getValue('//*[@id="QueueMonitor-grid"]/table/tbody/tr['.$i.']/td[1]//input');
            $model = User::model()->findByPk($pk);
            $values[] = "$model->extension";
        }
        $phpSortedValues = $values;
        usort ($phpSortedValues , function($a,$b) {
            $a = str_split((string)$a);
            $b = str_split((string)$b);
            
            foreach ($a as $key => $charFromA) {
                if ($charFromA == $b[$key]) {
                    continue;
                } else if ($charFromA > $b[$key]) {
                    return -1;
                } else {
                    return 1;
                }
            }
        });
        
        
        foreach ($phpSortedValues as $key => $value ) {
            
            $this->assertTrue($values[$key] == $value);
        }

        // Name DESC
        $this->click($xpathSortByNameLink);
        sleep(1); // wait for ajax response 
        $tableRowCount = $this->getXpathCount('//*[@id="QueueMonitor-grid"]//tbody//tr');
        $this->assertTrue($tableRowCount == 6);
        
        $values = array();
        for ($i = 6; $i >= 1; $i--) {
            $pk = $this->getValue('//*[@id="QueueMonitor-grid"]/table/tbody/tr['.$i.']/td[1]//input');
            $model = User::model()->findByPk($pk);
            $values[] = "$model->extension";
        }
        $phpSortedValues = $values;
        usort ($phpSortedValues , function($a,$b) {
            $a = str_split((string)$a);
            $b = str_split((string)$b);
            
            foreach ($a as $key => $charFromA) {
                if ($charFromA == $b[$key]) {
                    continue;
                } else if ($charFromA > $b[$key]) {
                    return 1;
                } else {
                    return -1;
                }
            }
        });

        foreach ($phpSortedValues as $key => $value ) {
            $this->assertTrue($values[$key] == $value);
        }
    }
}