{"size": 2039, "ext": "js", "max_stars_repo_path": "src/js/components/WinningNumbersInput.js", "max_stars_repo_name": "2SOOY/javascript-lotto", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/js/components/WinningNumbersInput.js", "max_issues_repo_name": "2SOOY/javascript-lotto", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/js/components/WinningNumbersInput.js", "max_forks_repo_name": "2SOOY/javascript-lotto", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 25.4875, "max_line_length": 80, "alphanum_fraction": 0.6625796959}
import { lottoManager } from './App.js';
import { $, $$, clearInputValue } from '../utils/dom.js';
import { isEmptyArray, isEmptyValue, isInRange } from '../utils/common.js';
import { ERROR_MESSAGE } from '../utils/message.js';
import { LOTTO } from '../utils/constants.js';

export default class WinningNumbersInput {
  constructor() {
    this.subscribeAction();
    this.selectDOM();
    this.bindEvent();
  }

  subscribeAction() {
    lottoManager.subscribe(this.render.bind(this));
  }

  selectDOM() {
    this.$target = $('#lotto-winning-number-input-container');
    this.$winningNumberInputs = $$('.winning-number');
    this.$bonusNumberInput = $('.bonus-number');
  }

  bindEvent() {
    this.$target.addEventListener('submit', e => {
      e.preventDefault();

      this.onShowWinningResult();
    });
  }

  onShowWinningResult() {
    const winningNumbers = this.$winningNumberInputs.map(({ value }) => value);
    const bonusNumber = this.$bonusNumberInput.value;

    const errorMessage = validateWinningNumbersInputValue(
      winningNumbers,
      bonusNumber,
    );
    if (errorMessage) {
      alert(errorMessage);
      return;
    }

    lottoManager.decideWinners(winningNumbers.map(Number), Number(bonusNumber));
  }

  render() {
    if (isEmptyArray(lottoManager.lottos)) {
      this.$target.classList.add('d-none');
      [...this.$winningNumberInputs, this.$bonusNumberInput].forEach(
        clearInputValue,
      );
      return;
    }

    this.$target.classList.remove('d-none');
  }
}

const validateWinningNumbersInputValue = (winningNumbers, bonusNumber) => {
  const numbers = [...winningNumbers, bonusNumber].map(Number);

  if (winningNumbers.some(isEmptyValue) || isEmptyValue(bonusNumber)) {
    return ERROR_MESSAGE.EMPTY_INPUT_NUMBER;
  }

  if (
    numbers.some(number => !isInRange(number, LOTTO.MIN_NUM, LOTTO.MAX_NUM))
  ) {
    return ERROR_MESSAGE.OUT_OF_RANGE;
  }

  if (new Set(numbers).size !== numbers.length) {
    return ERROR_MESSAGE.DUPLICATED_NUMBER;
  }

  return '';
};
