<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Override definitions for the upload repository type.
 * This is based on the file:
 * moodle/theme/boost/tests/behat/behat_theme_boost_behat_repository_upload.php
 *
 * @copyright  2018
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

// NOTE: no MOODLE_INTERNAL test here, this file may be required by behat before including /config.php.

require_once(__DIR__ . '/../../../../repository/upload/tests/behat/behat_repository_upload.php');

use Behat\Mink\Exception\ExpectationException as ExpectationException,
    Behat\Gherkin\Node\TableNode as TableNode;

/**
 * Override steps definitions to deal with the upload repository.
 *
 * @copyright  2018
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class behat_theme_snap_behat_repository_upload extends behat_repository_upload {

    protected function get_filepicker_node($filepickerelement) {

        // More info about the problem (in case there is a problem).
        $exception = new ExpectationException('"' . $filepickerelement . '" filepicker can not be found', $this->getSession());

        // If no file picker label is mentioned take the first file picker from the page.
        if (empty($filepickerelement)) {
            $filepickercontainer = $this->find(
                'xpath',
                "//*[@class=\"form-filemanager\"]",
                $exception
            );
        } else {
            // Gets the ffilemanager node specified by the locator which contains the filepicker container.
            $filepickerelement = behat_context_helper::escape($filepickerelement);
            $filepickercontainer = $this->find(
                'xpath',
                "//input[./@id = //label[normalize-space(.)=$filepickerelement]/@for]" .
                    "//ancestor::div[contains(concat(' ', normalize-space(@class), ' '), ' felement ')]",
                $exception
            );
        }

        return $filepickercontainer;
    }

    protected function open_add_file_window($filemanagernode, $repositoryname) {

        $exception = new ExpectationException('No files can be added to the specified filemanager', $this->getSession());

        // We should deal with single-file and multiple-file filemanagers,
        // catching the exception thrown by behat_base::find() in case is not multiple.
        try {
            // Looking for the add button inside the specified filemanager.
            $add = $this->find('css', 'div.fp-btn-add a', $exception, $filemanagernode);
        } catch (Exception $e) {
            // Otherwise should be a single-file filepicker form element.
            $add = $this->find('css', 'input.fp-btn-choose', $exception, $filemanagernode);
        }
        $this->ensure_node_is_visible($add);
        $add->click();

        // Wait for the default repository (if any) to load. This checks that
        // the relevant div exists and that it does not include the loading image.
        $this->ensure_element_exists(
            "//div[contains(concat(' ', normalize-space(@class), ' '), ' file-picker ')]" .
            "//div[contains(concat(' ', normalize-space(@class), ' '), ' fp-content ')]" .
            "[not(descendant::div[contains(concat(' ', normalize-space(@class), ' '), ' fp-content-loading ')])]",
            'xpath_element');

        // Getting the repository link and opening it.
        $repoexception = new ExpectationException('The "' . $repositoryname . '" repository has not been found',
            $this->getSession());

        // Avoid problems with both double and single quotes in the same string.
        $repositoryname = behat_context_helper::escape($repositoryname);

        // Here we don't need to look inside the selected element because there can only be one modal window.
        $repositorylink = $this->find(
            'xpath',
            "//div[contains(concat(' ', normalize-space(@class), ' '), ' fp-repo-area ')]" .
            "//descendant::span[contains(concat(' ', normalize-space(@class), ' '), ' fp-repo-name ')]" .
            "[normalize-space(.)=$repositoryname]",
            $repoexception
        );

        // Selecting the repo.
        $this->ensure_node_is_visible($repositorylink);
        if (!$repositorylink->getParent()->getParent()->hasClass('active')) {
            // If the repository link is active, then the repository is already loaded.
            // Clicking it while it's active causes issues, so only click it when it isn't (see MDL-51014).
            $repositorylink->click();
        }
    }

    protected function upload_file_to_filemanager($filepath, $filemanagerelement, TableNode $data, $overwriteaction = false) {
        global $CFG;

        $filemanagernode = $this->get_filepicker_node($filemanagerelement);

        // Opening the select repository window and selecting the upload repository.
        $this->open_add_file_window($filemanagernode, get_string('pluginname', 'repository_upload'));

        // Ensure all the form is ready.
        $noformexception = new ExpectationException('The upload file form is not ready', $this->getSession());
        $this->find(
            'xpath',
            "//div[contains(concat(' ', normalize-space(@class), ' '), ' container ')]" .
                "[contains(concat(' ', normalize-space(@class), ' '), ' repository_upload ')]" .
                "/descendant::div[contains(concat(' ', normalize-space(@class), ' '), ' file-picker ')]" .
                "/descendant::div[contains(concat(' ', normalize-space(@class), ' '), ' fp-content ')]" .
                "/descendant::div[contains(concat(' ', normalize-space(@class), ' '), ' fp-upload-form ')]" .
                "/descendant::form",
            $noformexception
        );
        // After this we have the elements we want to interact with.

        // Form elements to interact with.
        $file = $this->find_file('repo_upload_file');

        // Attaching specified file to the node.
        // Replace 'admin/' if it is in start of path with $CFG->admin .
        if (substr($filepath, 0, 6) === 'admin/') {
            $filepath = $CFG->dirroot . DIRECTORY_SEPARATOR . $CFG->admin .
                    DIRECTORY_SEPARATOR . substr($filepath, 6);
        }
        $filepath = str_replace('/', DIRECTORY_SEPARATOR, $filepath);
        if (!is_readable($filepath)) {
            $filepath = $CFG->dirroot . DIRECTORY_SEPARATOR . $filepath;
            if (!is_readable($filepath)) {
                throw new ExpectationException('The file to be uploaded does not exist.', $this->getSession());
            }
        }
        $file->attachFile($filepath);

        // Fill the form in Upload window.
        $datahash = $data->getRowsHash();

        // The action depends on the field type.
        foreach ($datahash as $locator => $value) {

            $field = behat_field_manager::get_form_field_from_label($locator, $this);

            // Delegates to the field class.
            $field->set_value($value);
        }

        // Submit the file.
        $submit = $this->find_button(get_string('upload', 'repository'));
        $submit->press();

        // We wait for all the JS to finish as it is performing an action.
        $this->getSession()->wait(behat_base::get_timeout(), self::PAGE_READY_JS);

        if ($overwriteaction !== false) {
            $overwritebutton = $this->find_button($overwriteaction);
            $this->ensure_node_is_visible($overwritebutton);
            $overwritebutton->click();

            // We wait for all the JS to finish.
            $this->getSession()->wait(behat_base::get_timeout(), self::PAGE_READY_JS);
        }

    }

}
