/* eslint no-console: "off" */
// 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/>.
/* jshint node: true, browser: false */
/* eslint-env node */

/**
 * Grunt configuration for local_treestudyplan
 *
 * @copyright  2023 P.M. Kuipers
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

/**
 * Grunt configuration.
 *
 * @param {Grunt} grunt
 */
module.exports = function(grunt) {
    const path = require('path');
    const process = require('process');
    const sass = require('sass');

    // Import grunt configuration for moodle base
    process.chdir("../.."); // Change dir to moodle base
    require(path.resolve(`./Gruntfile.js`))(grunt); // Run Gruntfile module from moodle base

    grunt.registerTask('scssplugin', 'Compile scss/styles.sccs into styles.css and css/devstyles.css', () => {

        const devoutput = 'css/devstyles.css';
        const prodoutput = 'styles.css';

        // Get full path of compenent and scss folder
        const componentPath = path.join(grunt.moodleEnv.gruntFilePath, grunt.moodleEnv.componentDirectory);
        const scssPath = path.join(componentPath, 'scss', 'styles.scss');
        console.log(`Compiling ${scssPath} including any imported files therein`);

        process.chdir(path.join(componentPath, 'scss'));
        const result = sass.compile(scssPath);
        if (result) {
            console.info("got result");

            // Some regex processing to match moodle stylelint styles

            // Change tab indent to 4 instead of 2
            let css = result.css.replace(/^ {2}([^ ])/gm, "    $1");

            // Insert a newline after every comma in a css selector
            // (only combined selectors will get that long)
            css = css.replace(/^[^ ].*[{,]$/gm, (m) => { // Find CSS selector lines
                return m.replace(/, /g, ",\n"); // Replace comma followed by space with comma newline
            });

            // Replace hex color codes with lowercase.
            const hexCodeToLower = (match, m1, m2) => {
                return '#' + m1.toLowerCase() + m2;
            };
            css = css.replace(/#([A-F0-9a-f]{3})([^A-F0-9a-f]?)/gm, hexCodeToLower); // 3 digit color codes
            css = css.replace(/#([A-F0-9a-f]{6})([^A-F0-9a-f]?)/gm, hexCodeToLower); // 6 digit color codes
            css = css.replace(/#([A-F0-9a-f]{8})([^A-F0-9a-f]?)/gm, hexCodeToLower); // 8 digit color codes (with alpha)

            // All other errors should really be fixed in the scss files :)

            [devoutput, prodoutput].forEach((output) => {
                console.info(`Storing ${output}`);
                grunt.file.write(path.join(componentPath, output), css);
            });
        }

    });

    // Rebuild on changes in the scss files when using 'grunt watch'
    grunt.config.merge({
        watch: {
            scssplugin: {
                files: ['scss/*.scss'],
                tasks: ['scssplugin']
            },
        },
    });

    // Remove gherkinlint from the startup list, since it exits with an error because of errors in moodle's own code
    grunt.moodleEnv.startupTasks.splice(grunt.moodleEnv.startupTasks.indexOf("gherkinlint"), 1);

    // Add the 'scssplugin' task as a startup task.
    grunt.moodleEnv.startupTasks.push('scssplugin');


};
