"use strict";

const {
  success: greenFn,
  error: redFn,
  warning: yellowFn,
  dim,
  symbols,
  isColorSupported,
} = require("./theme");

/**
 * Create a progress feedback instance.
 * Uses nanospinner when TTY + color supported; plain text otherwise.
 */
function createProgress() {
  const isTTY = !!(process.stdout && process.stdout.isTTY);

  if (isTTY && isColorSupported) {
    return createSpinnerProgress();
  }
  return createPlainProgress();
}

function createSpinnerProgress() {
  let createSpinner;
  try {
    ({ createSpinner } = require("nanospinner"));
  } catch {
    return createPlainProgress();
  }
  let spinner = null;

  return {
    start(text) {
      spinner = createSpinner(text, {
        mark: {
          complete: greenFn(symbols.complete),
          error: redFn(symbols.error),
        },
      }).start();
    },
    success(text, detail) {
      const msg = detail ? `${text}   ${dim(detail)}` : text;
      if (spinner) {
        spinner.success({ text: msg });
        spinner = null;
      } else {
        console.log(`${greenFn(symbols.complete)} ${msg}`);
      }
    },
    error(text) {
      if (spinner) {
        spinner.error({ text });
        spinner = null;
      } else {
        console.error(`${redFn(symbols.error)} ${text}`);
      }
    },
    warn(text) {
      if (spinner) {
        spinner.warn({ text });
        spinner = null;
      } else {
        console.log(`${yellowFn(symbols.progress)} ${text}`);
      }
    },
  };
}

function createPlainProgress() {
  return {
    start(text) {
      console.log(text + "...");
    },
    success(text, detail) {
      console.log("[x] " + text + (detail ? "   " + detail : ""));
    },
    error(text) {
      console.error("[!] " + text);
    },
    warn(text) {
      console.log("[>] " + text);
    },
  };
}

module.exports = { createProgress };
