<?php

use Facebook\WebDriver\Remote\RemoteWebElement;

/**
 * Inherited Methods
 * @method void wantToTest($text)
 * @method void wantTo($text)
 * @method void execute($callable)
 * @method void expectTo($prediction)
 * @method void expect($prediction)
 * @method void amGoingTo($argumentation)
 * @method void am($role)
 * @method void lookForwardTo($achieveValue)
 * @method void comment($description)
 * @method \Codeception\Lib\Friend haveFriend($name, $actorClass = NULL)
 *
 * @SuppressWarnings(PHPMD)
 */
class AcceptanceTester extends \Codeception\Actor
{
    use _generated\AcceptanceTesterActions;


    const SENDER_TERMINAL_ID          =  'GITLABSENDER';
    const SENDER_TERMINAL_PASSWORD    =  'G!TL4BS3NdEr';
    const RECEIVER_TERMINAL_ID        =  'GITLABRCIVER';
    const RECEIVER_TERMINAL_PASSWORD  =  'G!TL4BRC1VEr';
    const STANDART_PASSWORD           =  '123qwe';
    const USER_ADMIN                  =  'admin@cyberft.com';
    const USER_PODPISANT              =  'podpisant@cyberft.com';
    const USER_PODPISANT_NAME         =  'Подписатор Всея Терминала';
    const USER_OPERATOR               =  'operator@cyberft.com';
    const PLATINA_BIC                 =  '044525931';
    const RU_ACC_BANK_1               =  '30109810900000000330';
    const RU_ACC_BANK_2               =  '40702810200000000317';
    const US_ACC                      =  '40702840500000003031';
    const EUR_ACC                     =  '40701978200060002180';
    const RU_OGR_NAME                 =  'Организация CyberFT';
    const OGR_INN                     =  '6450013459';
    const ORG_KPP                     =  '645001001';
    const RU_OGR_ADDR_STR             =  'Краснопресненская набережная';
    const EN_ORG_NAME                 =  'CyberFT Organisation';
    const SIDEBAR                     =  '//div[@class=\'sidebar-left\']';
    const MENUBAR                     =  '//*[@id="mainmenu"]';
    const PLATINA_OFFICIAL_NAME       =  'ООО КБ "ПЛАТИНА"' ;

    /**
     * @param $link
     */
    public function recurCheckPage($link)
    {
        $I = $this;

        $ignore_pattern = [
            'monitor/log?page=',
            'dict-bank/update?id=',
            'dict-bank/delete?id=',
            '?sort=',
            '&sort=',
            '&mode=',
            'dict-bank/view?id=',
            '?page=',
            'site/login-key',
            'login-password',
            'login',
            'logout',
            'participantBIC=',
            'DocumentSearch',
            'SwiftFinSearch'
        ];

        $v_links = [
            '/logout',
            'javascript:;',
            '/ru/login',
            'http://cyberplat.ru'
        ];

        $I->amOnPage($link);
        $I->dontSee("Возникла внутренняя ошибка сервера");
        $I->dontSee("An internal server error occurred");

        $v_links[] = $link;

        $n_links = $I->grabMultiple('//a[not(contains(@href,"mailto"))]', 'href');

        $links = array_values(array_diff($n_links, $v_links));

        static $count=0;

        for ($n = 0; $n < count($links); $n++) {

            foreach ($ignore_pattern as $pattern) {
                preg_match("/" . preg_quote($pattern, '/') . "/", $links[$n], $matches);
                if (!empty($matches)) {
                    break 1;
                }
            }

            if (!empty($matches)) {
                //codecept_debug(print_r($matches, 1));
                continue;
            }

            if (in_array($links[$n], $v_links)) {
                continue;
            }

            $count++;
            $I->recurCheckPage($links[$n]);
        }

        codecept_debug(print_r($count, 1));
    }


    /**
     * @param $email
     * @param $password
     */
    public function loginUI($email, $password)
    {
        $I = $this;
        $I->amOnPage ('/login-password');
        $I->see ('Вход в систему');
        $I->fillField ('LoginPasswordForm[email]', $email);
        $I->fillField ('LoginPasswordForm[password]', $password);
        $I->click('//button[@class=\'btn btn-primary btn-block\']');
        $I->dontSee('Ошибка авторизации');
        try {
            $I->fuckthisui();
            $I->LeftMenuFix();
        } catch (Exception $e) {
        }
    }
    /**
     * @param $email
     * @param $password
     */
    public function login($email, $password)
    {
        $I = $this;
        $I->amOnPage('/login-password');
        $I->see('Вход в систему');
        $I->fillField('LoginPasswordForm[email]', $email);
        $I->fillField('LoginPasswordForm[password]', $password);
        $I->click('//button[@class=\'btn btn-primary btn-block\']');
        try {
            $I->waitForElement('//*[@id="mainmenu"]', 3);
        } catch (Exception $e) {
        }
    }
    /**
     * @throws Exception
     */
    public function fuckthisui()
    {
        $I = $this;
        try {
            $I->waitForElementChange (AcceptanceTester::SIDEBAR, function (Facebook\WebDriver\Remote\RemoteWebElement $element)
            {
                return $element->isDisplayed ();
            }, 5);
            $I->waitForElementChange (AcceptanceTester::MENUBAR, function (Facebook\WebDriver\Remote\RemoteWebElement $element) {
                return $element->isDisplayed ();
            }, 5);
        } catch (Exception $e) {
        }
    }

    /**
     * @param $xpath
     * @param $text
     * @throws Exception
     */
    public function SelectThis($xpath , $text)
    {
        $I = $this;
        $I->waitForElement ($xpath, '10');
        $I->seeElement($xpath);
        $I->click ($xpath);
        $I->dontSeeElement ('//li[contains(@class, \'select2-results__option select2-results__message\')]');
        $I->fillField ('//input[contains(@class, \'select2-search__field\')]', $text);
        $I->waitForElementChange ('//li[contains(@class, \'select2-results__option\')]', function (Facebook\WebDriver\Remote\RemoteWebElement $element) {
            return $element->isDisplayed ();
        }, 5);
        $I->waitForElementVisible ('//li[contains(@class, \'select2-results__option select2-results__option--highlighted\') and contains(text(),' . '"' . "$text" . '"' . ')]', '10');
        $I->jswait();
        try {
        $I->click ('//li[contains(@class, \'select2-results__option select2-results__option--highlighted\') and contains(text(),' . '"' . "$text" . '"' . ')]');
        $I->waitForElementChange ('//span[@class=\'select2-selection__rendered\']', function (Facebook\WebDriver\Remote\RemoteWebElement $element) {
        return $element->isDisplayed ();
        }, 5);
        //$I->waitForElementVisible ('//span[contains(@title,' . '"' . "$text" . '"' . ') or contains(text(),' . '"' . "$text " . '"' . ') and @class=\'select2-selection__rendered\']', '5');
        $I->waitForText ($text, '5', $xpath . '/preceding-sibling::*[1]');
        } catch (Exception $e) {
                 }

    }
    /**
     * @param $key
     * @param $value
     */
    public function saveLink($key, $value)
    {
        $data = unserialize(file_get_contents('_data/doc_links'));
        $data[$key] = $value;
        file_put_contents('_data/doc_links', serialize($data));
    }

    /**
     * @param $key
     * @return mixed
     */
    public function getLink($key)
    {
        $data = unserialize(file_get_contents('_data/doc_links'));
        return $data[$key];
    }

    /**
     * @param $xpath
     * @param $text
     */
    public function applyPageFilter($xpath, $text)
    {
        $I = $this;
        $I->seeElement($xpath);
        $I->waitForElementChange($xpath, function(Facebook\WebDriver\Remote\RemoteWebElement $element) {
            return $element->isDisplayed();
        }, 5);
        $I->fillField ($xpath,$text);
        try {
            $I->pressKey ($xpath, WebDriverKeys::ENTER);
            $I->waitForElementChange ($xpath, function (Facebook\WebDriver\Remote\RemoteWebElement $element) {
                return $element->isDisplayed ();
            }, 5);
            $I->waitForText ($text, '5');
        } catch (\Exception $ex) {
        }
    }



    /**
     * @param $xpath
     * @throws Exception
     */
    public function clearPageFilter($xpath)
    {
        $cnt = 0;
        $I = $this;
        while(true) {
            $I->fillField ($xpath,'');
            try {
                $I->pressKey ($xpath, WebDriverKeys::ENTER);
                $I->waitForElementChange($xpath,function(Facebook\WebDriver\Remote\RemoteWebElement $xpath) {
                    return $xpath->isDisplayed();
                }, 3);
                $I->waitForElementVisible ($xpath,3);
                $I->seeInField ($xpath,'');
                break;
            } catch (\Exception $ex) {
                if ($cnt < 30) {
                    $cnt++;
                } else {
                    throw $ex;
                }
            }
        }
    }

    /**
     *
     */
    public function NoWebErrors()
    {
        $I = $this;
        try {
            $I->dontsee ('Возникла внутренняя ошибка сервера.');
            $I->dontSee ("An internal server error occurred");
            $I->dontSee ("Call to a member");
            $I->dontSee ("Exception");
            $I->dontSee ("SQLSTATE");
        } catch (Exception $ex) {
        }
    }
    /**
     * @param $first
     * @param $second
     */
    public function GoSubMenu($first, $second)
    {
        $I = $this;
        try {
            $I->fuckthisui();
            $I->click ('//a[@id=' . '"' . $first . '"' . ']');
            $I->waitForElementVisible ('//a[@id=' . '"' . $first . '"' . ']/../ul/li/a[contains(text(),' . '"' . "$second" . '"' . ')]', '10');
            $I->scrollTo ('//a[@id=' . '"' . $first . '"' . ']/../ul/li/a[contains(text(),' . '"' . "$second" . '"' . ')]', '10');
            $I->click ('//a[@id=' . '"' . $first . '"' . ']/../ul/li/a[contains(text(),' . '"' . "$second" . '"' . ')]');
        } catch (Exception $ex) {
        }
    }

    /**
     *https://toster.ru/q/253330
     *         $I->executeJS("var script = document.createElement('script');script.type = 'text/javascript';script.src = 'https://code.jquery.com/jquery-1.8.3.js'; document.head.appendChild(script);");
     */
    public function jswait()
    {
        $I = $this;
        try {
            $I->waitForJS ('return document.readyState == "complete";', 5);
            $I->waitForJS ("return $.active == 0;", 5);
            $I->wait('0.1');
        } catch (\Exception $exception){
            }
    }

    /**
     * @param $beforesymbol
     * @return bool|string
     */
    public function CatchId()
    {
        $I = $this;
        $ID = (substr ($I->grabFromCurrentUrl (), strpos ($I->grabFromCurrentUrl (), '=') + strlen ('=')));
        return $ID;
    }

    /**
     * @param $dir
     * @return array
     */
    function dirToArray($dir)
    {
        $result = array();

        $cdir = scandir($dir);
        foreach ($cdir as $key => $value)
        {
            if (!in_array($value,array(".","..")))
            {
                if (is_dir($dir . DIRECTORY_SEPARATOR . $value))
                {
                    $result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value);
                }
                else
                {
                    $result[] = $value;
                }
            }
        }

        return $result;
    }
    /**
     *
     */
    public function LeftMenuFix()
    {
        $I = $this;
        $I->executeJS('document.getElementsByClassName("navbar navbar-inverse navbar-fixed-top")[0].style.position="absolute"');
        $I->executeJS('document.getElementsByClassName("sidebar-left")[0].style.position="absolute"');
    }
}
