/*
 * Copyright (C) Highsoft AS
 */

const gulp = require('gulp');
const log = require('./lib/log');

/**
 * Create the palette module file based on highcharts.scss
 *
 * @return {Promise<void>}
 *         Promise to keep
 */
async function task() {
    const fs = require('fs');
    const path = require('path');
    const lines = fs.readFileSync(
        path.join(__dirname, '../../css/highcharts.scss'), 'utf8'
    ).split('\n');

    let ts = '';
    lines.forEach((line, i) => {
        if (line.indexOf('$') === 0) {
            const parts = line
                .replace(' !default', '')
                .replace(/\r/, '').split(':');
            const key = parts[0].trim().replace(/^\$/, '')
                // Camelcase
                .replace(/-([a-z0-9])/g, g => g[1].toUpperCase());
            const val = parts[1].split(';')[0].trim();

            let comment = (line.split('//')[1] || '').trim();
            if (!comment && lines[i - 1].indexOf('/') === 0) {
                comment = lines[i - 1].replace(/^\/\/ /, '');
            }

            // Single color
            if (val.lastIndexOf('#') === 0) {
                ts += `    /**
     * ${comment}
     */
    ${key}: '${val}' as ColorString,\n`;

            // Array of colors
            } else if (val.lastIndexOf('#') > 0) {
                ts += `    /**
     * ${comment}
     */
    ${key}: [\n        '` +
                    val.replace(/ /g, '\',\n        \'') + '\'],\n';
            }
        }
    });

    const tpl =
`/**
 * Palette for Highcharts. Do not edit this file! This file is generated using
 * the 'gulp palette' task. Palette colors are defined in highcharts.scss.
 */
/* eslint comma-dangle: 0, max-len: 0 */
import type ColorString from './ColorString';
const palette = {
${ts}
};
export default palette;
`;
    const tsFilePath = path.join(__dirname, '../../ts/core/Color/Palette.ts');
    fs.writeFileSync(tsFilePath, tpl, 'utf8');

    log.success(`Wrote palette colors to ${tsFilePath}`);

}

gulp.task('palette', task);
