// Lint-scss Task
import gulp from 'gulp';
import postcss from 'gulp-postcss';
import reporter from 'postcss-reporter';
import syntaxSCSS from 'postcss-scss';
import notify from 'gulp-notify';
import stylelint from 'stylelint';
import cached from 'gulp-cached';

import { config } from '../config.mjs';
import { errorNotification } from "./setup.mjs";

let error = false;
let errorMessages = {};

/**
 * Linting for the Sass files: separate in functions.
 */
function _cssLint(src) {
  const processors = [
    stylelint({
      config: config.stylelintConfig,
      fix: true,
      files: src,
    }),
    reporter({
      clearMessages: true,
    }),
  ];

  return gulp.src(src, { base: './' })
    .pipe(cached(cssLint))
    .pipe(postcss(processors, { syntax: syntaxSCSS }))
    .pipe(cached(cssLint))
    .pipe(gulp.dest('./'));
}

const cssLintPrecommit = (done) => {
  error = false;
  errorMessages = {};
  const src = config.css.src;
  const processors = [
    stylelint({
      config: config.stylelintConfig,
      files: src,
    }),
    reporter({
      throwError: true,
      formatter: (input) => {
        if (Object.keys(input.messages).length) {
          error = true;
          input.messages.forEach((message) => {
            if (!errorMessages[message.line]) {
              errorMessages[message.line] = [];
            }
            errorMessages[message.line].push(message);
          });
        }
      },
    }),
  ];

  return gulp.src(config.css.src)
    .pipe(cached('cssLintPrecommit'))
    .pipe(postcss(processors, { syntax: syntaxSCSS }))
    .on('error', (err) => {
      errorNotification(this, err);
    })
    .on('end', () => {
      if (err) {
        Object.keys(errorMessages).forEach((line) => {
          errorMessages[line].forEach((message) => {
            notify(`${message.severity}: ${message.text} (${message.line}:${message.column})`);
          });
        });
        process.exitCode = 1;
      }
      done();
    });
};

/**
 * Use the functions in tasks.
 */

// ** for development.

// All css at once.
export const cssLintAll = () => _cssLint(config.css.src);

// Component's Theme css folder.
export const cssLintTheme = () => _cssLint(config.css.components.theme.src);

// Component's ContentBlocks css folder.
export const cssLintContentBlocks = () => _cssLint(config.css.components.contentblocks.src);

// Component's Features css folder.
export const cssLintFeatures = () => _cssLint(config.css.components.features.src);

export const cssLintSdc = () => _cssLint(config.css.src);

// ** Linting all CSS in precommit hook.
export const cssLintPrecommitTask = cssLintPrecommit;

/**
 * Run the tasks in bundles.
 */
export const cssLint = gulp.series(
  cssLintTheme,
  cssLintContentBlocks,
  cssLintFeatures,
  cssLintSdc
);
