"use strict";
const path = require("path");
const notifier = require("node-notifier");
const util = require("util");
const forkTsCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin");
const issue_1 = require("fork-ts-checker-webpack-plugin/lib/issue");
class ForkTsCheckerNotifierWebpackPlugin {
    constructor(options) {
        this.compilationDone = (diagnostics, lints) => {
            var notification = this.buildNotification([...diagnostics, ...lints]);
            if (notification) {
                notifier.notify(notification);
            }
        };
        this.options = options || {};
        this.lastBuildSucceeded = false;
        this.isFirstBuild = true;
        this.titlePrefix = this.options.title ? this.options.title + ' - ' : '';
    }
    buildNotification(issues) {
        if (this.isFirstBuild) {
            this.isFirstBuild = false;
            if (this.options.skipFirstNotification) {
                return undefined;
            }
        }
        var firstError = issues.find(issue => issue.severity === issue_1.IssueSeverity.ERROR);
        var firstWarning = issues.find(issue => issue.severity === issue_1.IssueSeverity.WARNING);
        if (firstError) {
            this.lastBuildSucceeded = false;
            return {
                title: util.format('%s%s', this.titlePrefix, 'Error in ' + path.basename(firstError.file || '')),
                message: firstError.message,
                icon: path.join(__dirname, 'images/error.png')
            };
        }
        if (firstWarning && !this.options.excludeWarnings) {
            this.lastBuildSucceeded = false;
            return {
                title: util.format('%s%s', this.titlePrefix, 'Warning in ' + path.basename(firstWarning.file || '')),
                message: firstWarning.message,
                icon: path.join(__dirname, 'images/warning.png')
            };
        }
        if (!this.options.skipSuccessful &&
            (!this.lastBuildSucceeded || this.options.alwaysNotify)) {
            this.lastBuildSucceeded = true;
            return {
                title: util.format('%sType check succeeded', this.titlePrefix),
                message: util.format('%s%s', 'No type errors!', firstWarning ? ' See warning(s) in console!' : ''),
                icon: path.join(__dirname, 'images/built.png')
            };
        }
    }
    apply(compiler) {
        // webpack 4+
        try {
            forkTsCheckerWebpackPlugin
                .getCompilerHooks(compiler)
                .receive.tap('fork-ts-checker-notifier-webpack-plugin', this.compilationDone);
        }
        catch (error) {
            console.error(`
        Something went wrong in accessing the hooks.
        Most likely the order of plugins is wrong.\n
        Check the documentation for "fork-ts-checker-notifier-webpack-plugin"\n
      `);
            throw Error(`Error: ${error}`);
        }
    }
}
module.exports = ForkTsCheckerNotifierWebpackPlugin;
