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

namespace mod_minilesson\output;

use core_plugin_manager;
use html_writer;
use moodle_url;
use mod_minilesson\constants;

/**
 * A custom renderer class that extends the plugin_renderer_base.
 *
 * @package mod_minilesson
 * @copyright COPYRIGHTNOTICE
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class rsquestion_renderer extends \plugin_renderer_base
{
    /**
     * Return HTML to display add first page links
     * @param \context $context
     * @param int $tableid
     * @return string
     */
    public function add_edit_page_links($context, $tableid, $region)
    {
        global $CFG;
        $itemid = 0;
        $config = get_config(constants::M_COMPONENT);

        $output = $this->output->heading(get_string("whatdonow", "minilesson"), 3);
        $links = [];

        $availableitems = core_plugin_manager::instance()->get_plugins_of_type(constants::SUBPLUGINTYPES['item']);
        // If modaleditform is true adding and editing item types is done in a popup modal. Thats good ...
        // but when there is a lot to be edited , a standalone page is better.
        // The modaleditform flag is acted on on additemlink template and rsquestionmanager js.
        $modaleditform = $config->modaleditform == "1";
        $allitems = [];
        $i = 0;
        /** @var \mod_minilesson\plugininfo\minilessonitem @qplugininfo */
        foreach ($availableitems as $qplugininfo) {
            if (!$qplugininfo->is_enabled()) {
                continue;
            }
            $i++;
            $addurl = new moodle_url(
                '/mod/minilesson/rsquestion/managersquestions.php',
                ['id' => $this->page->cm->id, 'type' => $qplugininfo->name]
            );
            $data = [
                'type' => $qplugininfo->name,
                'cmid' => $this->page->cm->id,
                'label' => (string) $qplugininfo->get_add_label(),
                'modaleditform' => $modaleditform,
                'imgsrc' => $qplugininfo->get_logo_url()->out(false),
                'description' => (string) $qplugininfo->get_description(),
                'videourl' => $qplugininfo->get_intro_video_url()->out(false),
                'addurl' => $addurl->out(false),
                'first' => $i == 1 ? true : false,
            ];
            $links[] = $this->render_from_template('mod_minilesson/additemlink', $data);
            $allitems[] = $data;
        }

        // Pass all lesson items to javascript via a hidden input field
        // It is too much data for js init call. It would complain about the size.
        // So we json encode it and pass the id of the hidden field
        // to js which will then fetch the data from the hidden field and parse it.
        $datatagid = 'lessonitems' . rand(1000, 9999);
        $datatag = html_writer::tag(
            'input',
            '',
            [
                'id' => $datatagid,
                'type' => 'hidden',
                'name' => 'lessonitems',
                'value' => json_encode($allitems),
            ]
        );

        $props = ['contextid' => $context->id, 'tableid' => $tableid, 'modaleditform' => $modaleditform,
        'wwwroot' => $CFG->wwwroot, 'cmid' => $this->page->cm->id, 'lessonitems' => $datatagid];
                $this->page->requires->js_call_amd(constants::M_COMPONENT . '/rsquestionmanager', 'init', [$props]);
        return $this->output->box(
            $output . $datatag . implode("", $links),
            'd-none generalbox firstpageoptions mod_minilesson_link_box_container'
        );
    }

    /**
     * Setup datatables for the items list
     * @param string $tableid
     */
    public function setup_datatables($tableid)
    {
        global $USER;

        $tableprops = [];
        $columns = [];
        $columns[0] = ['orderable' => false];
        $columns[1] = ['orderable' => false];
        $columns[2] = ['orderable' => false];
        $columns[3] = ['orderable' => false];
        $tableprops['columns'] = $columns;
        $tableprops['dom'] = 'lBfrtip';

        $noitemyet = html_writer::tag(
            'p',
            get_string('noitemyet', 'mod_minilesson'),
            ['class' => 'noitemyet']
        );
        $addingcontent = html_writer::tag(
            'p',
            get_string('addingcontent', 'mod_minilesson'),
            ['class' => 'addingcontent']
        );

        // Default ordering.
        $order = [];
        $order[0] = [1, "asc"];
        $tableprops['order'] = $order;
        $tableprops['language'] = [
            'emptyTable' => "$noitemyet$addingcontent",
        ];

        // Here we set up any info we need to pass into javascript.
        $opts = [];
        $opts['tableid'] = $tableid;
        $opts['tableprops'] = $tableprops;
        $this->page->requires->js_call_amd(constants::M_COMPONENT . "/datatables", 'init', [$opts]);
        $this->page->requires->css(new \moodle_url('https://cdn.datatables.net/1.13.7/css/jquery.dataTables.min.css'));
        $this->page->requires->css(new \moodle_url('https://cdn.datatables.net/buttons/3.2.0/css/buttons.dataTables.min.css'));
        $this->page->requires->strings_for_js(['bulkdelete', 'bulkdeletequestion'], constants::M_COMPONENT);
    }


    /**
     * Show a message when there are no items.
     * @param boolean $itemsvisible
     * @return string
     */
    public function show_noitems_message($itemsvisible)
    {
        $message = $this->output->heading(get_string('noitems', constants::M_COMPONENT), 3, 'main');
        $displayvalue = $itemsvisible ? 'none' : 'block';
        $ret = \html_writer::div(
            $message,
            constants::M_NOITEMS_CONT,
            [
                'id' => constants::M_NOITEMS_CONT,
                'style' => 'display: ' . $displayvalue,
            ]
        );
        return $ret;
    }

    /**
     * Return the html table of items
     * @param array homework objects
     * @param integer $courseid
     * @return string html of table
     */
    public function show_items_list($items, $minilesson, $cm, $visible)
    {
        global $CFG;
        // New code.
        $data = [];
        $data['tableid'] = constants::M_ITEMS_TABLE;
        $data['display'] = 'block';
        $itemsarray = [];
        $availableitems = core_plugin_manager::instance()->get_plugins_of_type(constants::SUBPLUGINTYPES['item']);

        foreach (array_values($items) as $i => $item) {
            $arrayitem = (array) $item;
            if (!array_key_exists($arrayitem['type'], $availableitems)) {
                continue;
            }
            /** @var \mod_minilesson\plugininfo\minilessonitem  $qplugininfo */
            $qplugininfo = $availableitems[$arrayitem['type']];
            $arrayitem['index'] = ($i + 1);
            $arrayitem['typelabel'] = strtoupper($qplugininfo->displayname);
            $arrayitem['icon'] = $qplugininfo->get_logo_url();
            $itemsarray[] = $arrayitem;
        }

        foreach (['arrowup', 'arrowdown', 'edit', 'copy', 'zoom', 'trash'] as $actionicon) {
            $data[$actionicon] = new moodle_url('/mod/minilesson/pix/' . $actionicon . '.svg', ['ver' => $CFG->themerev]);
        }

        $data['items'] = $itemsarray;

        $uppix = new \pix_icon('t/up', get_string('up'));
        $downpix = new \pix_icon('t/down', get_string('down'));
        $data['up'] = $uppix->export_for_pix();
        $data['down'] = $downpix->export_for_pix();
        $data['hasitems'] = count($itemsarray) > 0 ? true : false;
        $data['toggle'] = $CFG->branch > 500 ? 'toggler' : 'master';
        $data['target'] = $CFG->branch > 500 ? 'target' : 'slave';

        return $this->render_from_template('mod_minilesson/itemlist', $data);
    }
}
