<?php
// This file is part of mod_datalynx for Moodle - http://moodle.org/
//
// It 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.
//
// It 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/>.

/**
 *
 * @package datalynxfield_file
 * @subpackage file
 * @copyright 2013 onwards edulabs.org and associated programmers
 * @copyright based on the work  by 2011 Itamar Tzadok
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
namespace datalynxfield_file;

use html_writer;
use mod_datalynx\local\field\datalynxfield_renderer;
use moodle_url;
use MoodleQuickForm;
use stdClass;
use stored_file;

/**
 * Renderer for the file field type.
 */
class renderer extends datalynxfield_renderer {
    /**
     * Renders the edit mode form elements for this field.
     *
     * @param MoodleQuickForm $mform The Moodle form object.
     * @param stdClass $entry The entry object.
     * @param ?array $options Rendering options.
     * @return void
     */
    public function render_edit_mode(MoodleQuickForm &$mform, stdClass $entry, ?array $options = null) {
        $field = $this->field;
        $fieldid = $field->id();
        $entryid = $entry->id;

        $contentid = isset($entry->{"c{$fieldid}_id"}) ? $entry->{"c{$fieldid}_id"} : null;

        $fieldname = "field_{$fieldid}_{$entryid}";
        $fmoptions = [
                'subdirs' => 0,
                'maxbytes' => $field->get('param1'),
                'maxfiles' => $field->get('param2'),
                'accepted_types' => explode(',', $field->get('param3')),
        ];

        $draftitemid = file_get_submitted_draft_itemid("{$fieldname}_filemanager");

        file_prepare_draft_area(
            $draftitemid,
            $field->df()->context->id,
            'mod_datalynx',
            'content',
            $contentid,
            $fmoptions
        );

        // Add file manager element.
        $mform->addElement('filemanager', "{$fieldname}_filemanager", $field->name(), null, $fmoptions);
        $mform->setDefault("{$fieldname}_filemanager", $draftitemid);

        if (!empty($options['required'])) {
            $mform->addRule("{$fieldname}_filemanager", null, 'required', null, 'client');
        }
    }


    /**
     * Render the field of type file.
     *
     * @param stdClass $entry
     * @param array $options
     * @return string
     */
    public function render_display_mode(stdClass $entry, array $options): string {
        $field = $this->field;
        $fieldid = $field->id();
        $entryid = $entry->id;

        $content = $entry->{"c{$fieldid}_content"} ?? null;
        $content2 = $entry->{"c{$fieldid}_content2"} ?? null;
        $contentid = $entry->{"c{$fieldid}_id"} ?? null;

        if (empty($content)) {
            return '';
        }

        if (!empty($options['downloadcount'])) {
            return $content2;
        }

        $fs = get_file_storage();

        // Contentid is stored in itemid for lookup. This is usable with fieldgroups.
        $files = $fs->get_area_files(
            $field->df()->context->id,
            'mod_datalynx',
            'content',
            $contentid
        );
        if (!$files || !(count($files) > 1)) {
            return '';
        }

        $strfiles = [];
        foreach ($files as $file) {
            if (!$file->is_directory()) {
                $path = "/{$field->df()->context->id}/mod_datalynx/content/$contentid";
                // ToDo: Remove or implement altname.
                $altname = "";
                $strfiles[] = $this->display_file($file, $entryid, $path, $altname, $options);
            }
        }

        // For csv export we simply show link to first file.
        if (optional_param('exportcsv', '', PARAM_ALPHA)) {
            return $this->render_csv($strfiles);
        }

        return implode("<br />\n", $strfiles);
    }

    /**
     * Renders the search mode form elements for this field.
     *
     * @param MoodleQuickForm $mform
     * @param int $i
     * @param string $value
     * @return array
     */
    public function render_search_mode(MoodleQuickForm &$mform, int $i = 0, string $value = ''): array {
        $fieldid = $this->field->id();
        $fieldname = "f_{$i}_$fieldid";

        $arr = [];

        if ($mform->_formName == 'mod_datalynx_form_datalynx_customfilter_frontend_form') {
            $options = [
                    -1  => get_string('choose'),
                    1 => get_string('filemissing', 'datalynx'),
                    0 => get_string('fileexist', 'datalynx'),
            ];
            $arr[] = $mform->createElement('select', $fieldname, '', $options);
            $mform->setType($fieldname, PARAM_INT);
            $mform->setDefault($fieldname, $value);
        } else {
            $arr[] = &$mform->createElement('text', $fieldname, null, ['size' => '32']);
            $mform->setType($fieldname, PARAM_NOTAGS);
            $mform->setDefault($fieldname, $value ? 1 : 0);
            $mform->disabledIf($fieldname, "searchoperator$i", 'eq', '');
        }
        return [$arr, null];
    }

    /**
     * Render file html.
     *
     * @param stored_file $file
     * @param int $entryid
     * @param string $path
     * @param string $altname
     * @param ?array $params
     * @return moodle_url|string
     */
    protected function display_file(stored_file $file, int $entryid, string $path, string $altname = '', ?array $params = null) {
        $field = $this->field;
        $fieldid = $field->id();
        $fieldname = "field_{$fieldid}_{$entryid}";
        $filename = $file->get_filename();
        $mimetype = $file->get_mimetype();
        $pluginfileurl = '/pluginfile.php';

        // Check for specific parameters/patterns first.
        if (!empty($params['url'])) {
            return moodle_url::make_file_url($pluginfileurl, "$path/$filename");
        } else if (!empty($params['size'])) {
            $bsize = $file->get_filesize();
            if ($bsize < 1000000) {
                $size = round($bsize / 1000, 1) . 'KB';
            } else {
                $size = round($bsize / 1000000, 1) . 'MB';
            }
            return $size;
        } else if (!empty($params['content'])) {
            return $file->get_content();
        } else if (!empty($params['download'])) {
            return $this->display_link($file, $path, $altname, $params);
        }

        // Embed PDF if it's a PDF file and no specific pattern was requested.
        if ($mimetype === 'application/pdf') {
            // PDF document.
            $moodleurl = moodle_url::make_file_url($pluginfileurl, "$path/$filename");
            return $this->embed_pdf($moodleurl->out(), $fieldname);
        }

        // For all other file types, display as link.
        return $this->display_link($file, $path, $altname, $params);
    }

    // phpcs:disable moodle.PHP.ForbiddenGlobalUse.BadGlobal
    /**
     * Returns general link or pdf embedding html.
     * @param string $fullurl
     * @param string $fieldname
     * @return string html
     */
    protected function embed_pdf(string $fullurl, string $fieldname): string {
        global $PAGE;
        $customscale = $this->field->get('param4');
        if (empty($customscale)) {
            $customscale = 1;
        }
        $pdfmoduleurl = (new moodle_url('/mod/datalynx/pdfjs/pdf.mjs'))->out(false);
        $moduleloader = html_writer::script(
            'if (!window.modDatalynxPdfJsModulePromise) {' .
                ' window.modDatalynxPdfJsModulePromise = import(' . json_encode($pdfmoduleurl) . ')' .
                '.then((pdfJs) => {' .
                    ' window.modDatalynxPdfJsModule = pdfJs;' .
                    ' return pdfJs;' .
                '});' .
            '}',
            ['type' => 'module']
        );
        $PAGE->requires->js_call_amd(
            'mod_datalynx/pdfembed',
            'renderPDF',
            [$fullurl, $fieldname, $customscale]
        );

        return '<div><a href="' . $fullurl . '" target="_blank" class="btn btn-primary">' .
                get_string('download', 'core_repository') . ' ' .
                get_string('application/pdf', 'core_mimetypes') . '</a></div><br>
        <div style="width: 1800px; min-height: 1400px;" id="' . $fieldname . '"></div>
        ' . $moduleloader;
    }
    // phpcs:enable moodle.PHP.ForbiddenGlobalUse.BadGlobal

    // phpcs:disable moodle.PHP.ForbiddenGlobalUse.BadGlobal
    /**
     * Render a link.
     * @param stored_file $file
     * @param string $path
     * @param string $altname
     * @param ?array $params
     * @return string
     */
    protected function display_link($file, $path, $altname, $params = null): string {
        global $OUTPUT;

        $filename = $file->get_filename();
        $mimetype = $file->get_mimetype();
        $displayname = $altname ?: $filename;
        $fileicon = html_writer::empty_tag(
            'img',
            ['src' => $OUTPUT->image_url(file_mimetype_icon($mimetype)),
            'alt' => $mimetype,
            'height' => 16,
            'width' => 16]
        );

        if (!empty($params['download'])) {
            [, $context, , , $contentid] = explode('/', $path);
            $url = new moodle_url(
                "/mod/datalynx/field/file/download.php",
                ['cid' => $contentid, 'context' => $context, 'file' => $filename]
            );
            return html_writer::link($url, "$fileicon&nbsp;$displayname", ['target' => '_blank']);
        } else {
            $url = moodle_url::make_file_url('/pluginfile.php', "$path/$filename");
        }

        return html_writer::link($url, "$fileicon&nbsp;$displayname");
    }
    // phpcs:enable moodle.PHP.ForbiddenGlobalUse.BadGlobal

    /**
     * Returns pluginfile URL patterns supported by this field.
     */
    public function pluginfile_patterns(): array {
        return ["[[{$this->field->name()}]]"];
    }

    /**
     * Array of patterns this field supports
     */
    protected function patterns(): array {
        $fieldname = $this->field->name();

        $patterns = parent::patterns();
        $patterns["[[$fieldname]]"] = [true];
        $patterns["[[$fieldname:url]]"] = [false];
        $patterns["[[$fieldname:alt]]"] = [true];
        $patterns["[[$fieldname:size]]"] = [false];
        $patterns["[[$fieldname:content]]"] = [false];
        $patterns["[[$fieldname:download]]"] = [false];
        $patterns["[[$fieldname:downloadcount]]"] = [false];

        return $patterns;
    }

    /**
     * Returns comma seperated list of urls in this entry.
     *
     * @param array $strfiles Array of HTML strings containing file links.
     * @return string Comma-separated list of URLs.
     */
    public function render_csv($strfiles): string {
        $regex = '/https?\:\/\/[^\" ]+/i';
        $matches = [];
        foreach ($strfiles as $strfile) {
            preg_match($regex, $strfile, $match);
            $matches[] = $match[0];
        }

        return implode(",", $matches);
    }
}
