<?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/>.

declare(strict_types=1);

namespace core_tag\reportbuilder\datasource;

use core\context\{course, user};
use core_reportbuilder_generator;
use core_reportbuilder\local\filters\{boolean_select, date, number, select, tags as tags_filter};
use core_reportbuilder\tests\core_reportbuilder_testcase;

/**
 * Unit tests for tags datasource
 *
 * @package     core_tag
 * @covers      \core_tag\reportbuilder\datasource\tags
 * @copyright   2022 Paul Holden <paulh@moodle.com>
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
final class tags_test extends core_reportbuilder_testcase {

    /**
     * Test default datasource
     */
    public function test_datasource_default(): void {
        $this->resetAfterTest();

        $user = $this->getDataGenerator()->create_user(['interests' => ['Pies']]);
        $course = $this->getDataGenerator()->create_course(['tags' => ['Horses']]);

        /** @var core_reportbuilder_generator $generator */
        $generator = $this->getDataGenerator()->get_plugin_generator('core_reportbuilder');
        $report = $generator->create_report(['name' => 'Tags', 'source' => tags::class, 'default' => 1]);

        $content = $this->get_custom_report_content($report->get('id'));
        $this->assertCount(2, $content);

        // Default columns are collection, tag (with link), standard, context. Sorted by collection and tag.
        [$collection, $tag, $standard, $context] = array_values($content[0]);
        $this->assertEquals('Default collection', $collection);
        $this->assertStringContainsString('Horses', $tag);
        $this->assertEquals('No', $standard);
        $this->assertEquals(course::instance($course->id)->get_context_name(), $context);

        [$collection, $tag, $standard, $context] = array_values($content[1]);
        $this->assertEquals('Default collection', $collection);
        $this->assertStringContainsString('Pies', $tag);
        $this->assertEquals('No', $standard);
        $this->assertEquals(user::instance($user->id)->get_context_name(), $context);
    }

    /**
     * Test datasource columns that aren't added by default
     */
    public function test_datasource_non_default_columns(): void {
        $this->resetAfterTest();

        $this->getDataGenerator()->create_tag(['name' => 'Horses', 'description' => 'Neigh', 'flag' => 2]);
        $course = $this->getDataGenerator()->create_course(['tags' => ['Horses']]);

        /** @var core_reportbuilder_generator $generator */
        $generator = $this->getDataGenerator()->get_plugin_generator('core_reportbuilder');
        $report = $generator->create_report(['name' => 'Tags', 'source' => tags::class, 'default' => 0]);

        // Collection.
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'collection:default']);
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'collection:component']);
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'collection:searchable']);
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'collection:customurl']);

        // Tag.
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'tag:name']);
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'tag:namewithbadge']);
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'tag:description']);
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'tag:flagged']);
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'tag:flagcount']);
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'tag:timemodified']);

        // Context.
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'context:name']);

        // Instance.
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'instance:area']);
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'instance:component']);
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'instance:itemtype']);
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'instance:itemid']);
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'instance:timecreated']);
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'instance:timemodified']);

        $content = $this->get_custom_report_content($report->get('id'));
        $this->assertCount(1, $content);

        [
            $collectiondefault,
            $collectioncomponent,
            $collectionsearchable,
            $collectioncustomurl,
            $tagname,
            $tagnamewithbadge,
            $tagdescription,
            $tagflagged,
            $tagflagcount,
            $tagtimemodified,
            $contextname,
            $instancearea,
            $instancecomponent,
            $instanceitemtype,
            $instanceitemid,
            $instancetimecreated,
            $instancetimemodified,
        ] = array_values($content[0]);

        // Collection.
        $this->assertEquals('Yes', $collectiondefault);
        $this->assertEmpty($collectioncomponent);
        $this->assertEquals('Yes', $collectionsearchable);
        $this->assertEmpty($collectioncustomurl);

        // Tag.
        $this->assertEquals('Horses', $tagname);
        $this->assertEquals('<span class="badge bg-info text-white"><span class="flagged-tag">Horses</span></span>',
            $tagnamewithbadge);
        $this->assertEquals('<div class="text_to_html">Neigh</div>', $tagdescription);
        $this->assertEquals('Yes', $tagflagged);
        $this->assertEquals(2, $tagflagcount);
        $this->assertNotEmpty($tagtimemodified);

        // Context.
        $this->assertEquals(course::instance($course->id)->get_context_name(), $contextname);

        // Instance.
        $this->assertEquals('Courses', $instancearea);
        $this->assertEquals('core', $instancecomponent);
        $this->assertEquals('course', $instanceitemtype);
        $this->assertEquals($course->id, $instanceitemid);
        $this->assertNotEmpty($instancetimecreated);
        $this->assertNotEmpty($instancetimemodified);
    }

    /**
     * Data provider for {@see test_datasource_filters}
     *
     * @return array[]
     */
    public static function datasource_filters_provider(): array {
        return [
            // Collection.
            'Filter collection name' => ['collection:name', [
                'collection:name_operator' => select::NOT_EQUAL_TO,
                'collection:name_value' => -1,
            ], true],
            'Filter collection default' => ['collection:default', [
                'collection:default_operator' => boolean_select::CHECKED,
            ], true],
            'Filter collection default (no match)' => ['collection:default', [
                'collection:default_operator' => boolean_select::NOT_CHECKED,
            ], false],
            'Filter collection searchable' => ['collection:searchable', [
                'collection:searchable_operator' => boolean_select::CHECKED,
            ], true],
            'Filter collection searchable (no match)' => ['collection:searchable', [
                'collection:searchable_operator' => boolean_select::NOT_CHECKED,
            ], false],

            // Tag.
            'Filter tag name equal to' => ['tag:name', [
                'tag:name_operator' => tags_filter::EQUAL_TO,
                'tag:name_value' => [-1],
            ], false],
            'Filter tag name not equal to' => ['tag:name', [
                'tag:name_operator' => tags_filter::NOT_EQUAL_TO,
                'tag:name_value' => [-1],
            ], true],
            'Filter tag name empty' => ['tag:name', [
                'tag:name_operator' => tags_filter::EMPTY,
            ], false],
            'Filter tag name not empty' => ['tag:name', [
                'tag:name_operator' => tags_filter::NOT_EMPTY,
            ], true],
            'Filter tag standard' => ['tag:standard', [
                'tag:standard_operator' => boolean_select::NOT_CHECKED,
            ], true],
            'Filter tag standard (no match)' => ['tag:standard', [
                'tag:standard_operator' => boolean_select::CHECKED,
            ], false],
            'Filter tag flagged' => ['tag:flagged', [
                'tag:flagged_operator' => boolean_select::CHECKED,
            ], true],
            'Filter tag flagged (no match)' => ['tag:flagged', [
                'tag:flagged_operator' => boolean_select::NOT_CHECKED,
            ], false],
            'Filter tag flag count' => ['tag:flagcount', [
                'tag:flagcount_operator' => number::GREATER_THAN,
                'tag:flagcount_value1' => 1,
            ], true],
            'Filter tag flag count (no match)' => ['tag:flagcount', [
                'tag:flagcount_operator' => number::EQUAL_TO,
                'tag:flagcount_value1' => 0,
            ], false],
            'Filter tag time modified' => ['tag:timemodified', [
                'tag:timemodified_operator' => date::DATE_RANGE,
                'tag:timemodified_from' => 1622502000,
            ], true],
            'Filter tag time modified (no match)' => ['tag:timemodified', [
                'tag:timemodified_operator' => date::DATE_RANGE,
                'tag:timemodified_to' => 1622502000,
            ], false],

            // Instance.
            'Filter instance tag area' => ['instance:area', [
                'instance:area_operator' => select::EQUAL_TO,
                'instance:area_value' => 'core/course',
            ], true],
            'Filter instance tag area (no match)' => ['instance:area', [
                'instance:area_operator' => select::NOT_EQUAL_TO,
                'instance:area_value' => 'core/course',
            ], false],
            'Filter instance time created' => ['instance:timecreated', [
                'instance:timecreated_operator' => date::DATE_RANGE,
                'instance:timecreated_from' => 1622502000,
            ], true],
            'Filter instance time created (no match)' => ['instance:timecreated', [
                'instance:timecreated_operator' => date::DATE_RANGE,
                'instance:timecreated_to' => 1622502000,
            ], false],
            'Filter instance time modified' => ['instance:timemodified', [
                'instance:timemodified_operator' => date::DATE_RANGE,
                'instance:timemodified_from' => 1622502000,
            ], true],
            'Filter instance time modified (no match)' => ['instance:timemodified', [
                'instance:timemodified_operator' => date::DATE_RANGE,
                'instance:timemodified_to' => 1622502000,
            ], false],
        ];
    }

    /**
     * Test datasource filters
     *
     * @param string $filtername
     * @param array $filtervalues
     * @param bool $expectmatch
     *
     * @dataProvider datasource_filters_provider
     */
    public function test_datasource_filters(
        string $filtername,
        array $filtervalues,
        bool $expectmatch
    ): void {
        $this->resetAfterTest();

        $this->getDataGenerator()->create_tag(['name' => 'Horses', 'flag' => 2]);
        $this->getDataGenerator()->create_course(['tags' => ['Horses']]);

        /** @var core_reportbuilder_generator $generator */
        $generator = $this->getDataGenerator()->get_plugin_generator('core_reportbuilder');

        // Create report containing single tag name, and given filter.
        $report = $generator->create_report(['name' => 'Tags', 'source' => tags::class, 'default' => 0]);
        $generator->create_column(['reportid' => $report->get('id'), 'uniqueidentifier' => 'tag:name']);

        // Add filter, set it's values.
        $generator->create_filter(['reportid' => $report->get('id'), 'uniqueidentifier' => $filtername]);
        $content = $this->get_custom_report_content($report->get('id'), 0, $filtervalues);

        if ($expectmatch) {
            $this->assertCount(1, $content);
            $this->assertEquals('Horses', reset($content[0]));
        } else {
            $this->assertEmpty($content);
        }
    }

    /**
     * Stress test datasource
     *
     * In order to execute this test PHPUNIT_LONGTEST should be defined as true in phpunit.xml or directly in config.php
     */
    public function test_stress_datasource(): void {
        if (!PHPUNIT_LONGTEST) {
            $this->markTestSkipped('PHPUNIT_LONGTEST is not defined');
        }

        $this->resetAfterTest();

        $this->getDataGenerator()->create_course(['tags' => ['Horses']]);

        $this->datasource_stress_test_columns(tags::class);
        $this->datasource_stress_test_columns_aggregation(tags::class);
        $this->datasource_stress_test_conditions(tags::class, 'tag:name');
    }
}
