/**
 * `list` type prompt
 */

import ansiEscapes from 'ansi-escapes';
import colors from 'yoctocolors-cjs';
import figures from '@inquirer/figures';
import { map, takeUntil } from 'rxjs';
import observe from '../utils/events.js';
import Paginator from '../utils/paginator.js';
import incrementListIndex from '../utils/incrementListIndex.js';
import Base from './base.js';

export default class CheckboxPrompt extends Base {
  constructor(questions, rl, answers) {
    super(questions, rl, answers);

    if (!this.opt.choices) {
      this.throwParamError('choices');
    }

    if (Array.isArray(this.opt.default)) {
      for (const choice of this.opt.choices) {
        if (this.opt.default.includes(choice.value)) {
          choice.checked = true;
        }
      }
    }

    this.pointer = 0;

    // Make sure no default is set (so it won't be printed)
    this.opt.default = null;

    const shouldLoop = this.opt.loop === undefined ? true : this.opt.loop;
    this.paginator = new Paginator(this.screen, { isInfinite: shouldLoop });
  }

  /**
   * Start the Inquiry session
   * @param  {Function} cb      Callback when prompt is done
   * @return {this}
   */

  _run(cb) {
    this.done = cb;

    const events = observe(this.rl);

    const validation = this.handleSubmitEvents(
      events.line.pipe(map(this.getCurrentValue.bind(this))),
    );
    validation.success.forEach(this.onEnd.bind(this));
    validation.error.forEach(this.onError.bind(this));

    events.normalizedUpKey
      .pipe(takeUntil(validation.success))
      .forEach(this.onUpKey.bind(this));
    events.normalizedDownKey
      .pipe(takeUntil(validation.success))
      .forEach(this.onDownKey.bind(this));
    events.numberKey
      .pipe(takeUntil(validation.success))
      .forEach(this.onNumberKey.bind(this));
    events.spaceKey
      .pipe(takeUntil(validation.success))
      .forEach(this.onSpaceKey.bind(this));
    events.aKey.pipe(takeUntil(validation.success)).forEach(this.onAllKey.bind(this));
    events.iKey.pipe(takeUntil(validation.success)).forEach(this.onInverseKey.bind(this));

    // Init the prompt
    this.render();
    this.firstRender = false;

    return this;
  }

  /**
   * Render the prompt to screen
   * @return {CheckboxPrompt} self
   */

  render(error) {
    // Render question
    let message = this.getQuestion();
    let bottomContent = '';

    if (!this.dontShowHints) {
      message +=
        '(Press ' +
        colors.cyan(colors.bold('<space>')) +
        ' to select, ' +
        colors.cyan(colors.bold('<a>')) +
        ' to toggle all, ' +
        colors.cyan(colors.bold('<i>')) +
        ' to invert selection, and ' +
        colors.cyan(colors.bold('<enter>')) +
        ' to proceed)';
    }

    // Render choices or answer depending on the state
    if (this.status === 'answered') {
      message += colors.cyan(this.selection.join(', '));
    } else {
      const choicesStr = renderChoices(this.opt.choices, this.pointer);
      const indexPosition = this.opt.choices.indexOf(
        this.opt.choices.getChoice(this.pointer),
      );
      const realIndexPosition =
        this.opt.choices.reduce((acc, value, i) => {
          // Dont count lines past the choice we are looking at
          if (i > indexPosition) {
            return acc;
          }
          // Add line if it's a separator
          if (value.type === 'separator') {
            return acc + 1;
          }

          let l = value.name;
          // Non-strings take up one line
          if (typeof l !== 'string') {
            return acc + 1;
          }

          // Calculate lines taken up by string
          l = l.split('\n');
          return acc + l.length;
        }, 0) - 1;
      message +=
        '\n' + this.paginator.paginate(choicesStr, realIndexPosition, this.opt.pageSize);
    }

    if (error) {
      bottomContent = colors.red('>> ') + error;
    }

    message += ansiEscapes.cursorHide;

    this.screen.render(message, bottomContent);
  }

  /**
   * When user press `enter` key
   */

  onEnd(state) {
    this.status = 'answered';
    this.dontShowHints = true;
    // Rerender prompt (and clean subline error)
    this.render();

    this.screen.done();
    this.done(state.value);
  }

  onError(state) {
    this.render(state.isValid);
  }

  getCurrentValue() {
    const choices = this.opt.choices.filter(
      (choice) => Boolean(choice.checked) && !choice.disabled,
    );

    this.selection = choices.map((choice) => choice.short);
    return choices.map((choice) => choice.value);
  }

  onUpKey() {
    this.pointer = incrementListIndex(this.pointer, 'up', this.opt);
    this.render();
  }

  onDownKey() {
    this.pointer = incrementListIndex(this.pointer, 'down', this.opt);
    this.render();
  }

  onNumberKey(input) {
    if (input <= this.opt.choices.realLength) {
      this.pointer = input - 1;
      this.toggleChoice(this.pointer);
    }

    this.render();
  }

  onSpaceKey() {
    this.toggleChoice(this.pointer);
    this.render();
  }

  onAllKey() {
    const shouldBeChecked = this.opt.choices.some(
      (choice) => choice.type !== 'separator' && !choice.checked,
    );

    this.opt.choices.forEach((choice) => {
      if (choice.type !== 'separator') {
        choice.checked = shouldBeChecked;
      }
    });

    this.render();
  }

  onInverseKey() {
    this.opt.choices.forEach((choice) => {
      if (choice.type !== 'separator') {
        choice.checked = !choice.checked;
      }
    });

    this.render();
  }

  toggleChoice(index) {
    const item = this.opt.choices.getChoice(index);
    if (item !== undefined) {
      this.opt.choices.getChoice(index).checked = !item.checked;
    }
  }
}

/**
 * Function for rendering checkbox choices
 * @param  {Number} pointer Position of the pointer
 * @return {String}         Rendered content
 */

function renderChoices(choices, pointer) {
  let output = '';
  let separatorOffset = 0;

  choices.forEach((choice, i) => {
    if (choice.type === 'separator') {
      separatorOffset++;
      output += ' ' + choice + '\n';
      return;
    }

    if (choice.disabled) {
      separatorOffset++;
      output += ' - ' + choice.name;
      output += ` (${
        typeof choice.disabled === 'string' ? choice.disabled : 'Disabled'
      })`;
    } else {
      const line = getCheckbox(choice.checked) + ' ' + choice.name;
      output +=
        i - separatorOffset === pointer
          ? colors.cyan(figures.pointer + line)
          : ' ' + line;
    }

    output += '\n';
  });

  return output.replaceAll(/\n$/g, '');
}

/**
 * Get the checkbox
 * @param  {Boolean} checked - add a X or not to the checkbox
 * @return {String} Composited checkbox string
 */

function getCheckbox(checked) {
  return checked ? colors.green(figures.radioOn) : figures.radioOff;
}
