// DinoWorks JavaScript Library 2023-09-23

class CheckTextValidation {
  // constructor
  constructor(selector, options) {
    this.selector = selector;
    this.node = document.querySelector(selector);
    this.container = this.node.closest('div');
    this.actionBtn = this.container.querySelector('a.btn');
    this.options = options;
    this.onChangeCheck = false;
    this.timerId = '';

    this.setEvent();
  }

  // 이벤트 정의 (위임방식)
  setEvent() {
    const selector = this.selector;
    const that = this;

    // input 이벤트
    document.addEventListener('input', function(e) {
      let lastNode = e.currentTarget;  // #document (html 요소)
      let nodeNow = e.target;
      while (nodeNow !== lastNode) {
        if (nodeNow.matches(selector) === true) {
          console.log(that.onChangeCheck);
          if (that.onChangeCheck === true) that.checkValidation();
        }
        nodeNow = nodeNow.parentNode;
      }
    }, false);

    // focusout 이벤트
    document.addEventListener('focusout', function(e) {
      let lastNode = e.currentTarget;  // #document (html 요소)
      let nodeNow = e.target;
      while (nodeNow !== lastNode) {
        if (nodeNow.matches(selector) === true) {
          that.checkValidation();
          that.onChangeCheck = true;     // input시 계속 체크
        }
        nodeNow = nodeNow.parentNode;
      }
    }, false);
  }

  // 유효성 검사
  checkValidation() {
    let value = this.node.value;
    let options = this.options;
    let isValid = true;

    for (let i = 0; i < options.length; i++) {
      let result = options[i].regExpText.test(value);
      // console.log(node, value, options[i].type, options[i].regExpText, result);
      if ((options[i].type === 'match' && result === true) || (options[i].type === 'not-match' && result === false)) {
        this.displayError(options[i].message);
        isValid = false;    // 1개라도 통과되지 않으면 false
        break;
      }
    }

    // 모든 검사 통과시 true 유지
    if (isValid === true) this.displayValid();

    return isValid;
  }

  // 에러 메세지 표시
  displayError(msg) {
    const container = this.container;
    const msgNode = this.container.querySelector('span.message');
    const actionBtn = this.actionBtn;

    container.classList.add('error');
    container.insertAdjacentHTML('beforeend', `<span class="message">${msg}</span>`);
    if (msgNode !== null) msgNode.remove();
    if (actionBtn !== null) actionBtn.classList.add('disabled');
  }

  // 초기상태(유효성 검사 통과)
  displayValid() {
    const container = this.container;
    const msgNode = this.container.querySelector('span.message');
    const actionBtn = this.actionBtn;

    container.classList.remove('error');
    if (msgNode !== null) msgNode.remove();
    if (actionBtn !== null) actionBtn.classList.remove('disabled');
  }

  isValid() {
    let value = this.node.value;
    let options = this.options;
    let isValid = true;

    for (let i = 0; i < options.length; i++) {
      let result = options[i].regExpText.test(value);
      if ((options[i].type === 'match' && result === true) || (options[i].type === 'not-match' && result === false)) {
        isValid = false;
        break;
      }
    }

    return isValid;
  }

  startTimer(minute) {
    const container = this.container;
    let seconds = minute * 60;     // 초 단위로 환산
    let time = secondsToExpress(seconds);
    let timerId = this.timerId;

    container.classList.add('timer');
    container.insertAdjacentHTML('beforeend', `<span class="timer">${time}</span>`);

    timerId = setInterval(function() {
      seconds--;
      time = secondsToExpress(seconds);
      container.querySelector('span.timer').innerText = time;
      if (seconds === 0) clearInterval(timerId);
    }, 1000);


    function secondsToExpress(seconds, type = 'min') {
      let hour = parseInt(seconds / 3600);
      let min = parseInt((seconds - (hour * 3600)) / 60);
      let sec = parseInt(seconds - (hour * 3600) - (min * 60));
      hour = hour < 10 ? '0' + hour : hour.toString();
      sec = sec < 10 ? '0' + sec : sec.toString();

      if (type === 'hour') {
        min = min < 10 ? '0' + min : min.toString();
        return hour + ':' + min + ':' + sec;
      } else {
        return min + ':' + sec;
      }
    }
  }
}












/*
class DinoElement {
  constructor(selector) {

    console.log(selector);

    if (typeof(selector) === 'string') {
      this.nodes = document.querySelectorAll(selector);
    } else {
      this.nodes = selector;
    }
    if (this.nodes.length === 0) {
      console.log(`${selector}에 해당하는 요소가 존재하지 않습니다.`);
    } else {
      console.log(this.nodes);
    }
  }

  // 이벤트 위임 방식으로 적용
  addEvent(eventType, action, option) {
    const nodes = this.nodes;
    const selector = this.selector;
    document.addEventListener(eventType, function(e) {
      let lastNode = e.currentTarget;
      let nodeNow = e.target;
      while (nodeNow !== lastNode) {
        if (nodeNow.matches(selector) === true || nodes === nodeNow) {
          action(e);
        }
        nodeNow = nodeNow.parentNode;
      }
    }, option);
  }

  addEvent(eventType, action, option) {
    const elements = this.nodes;
    elements.forEach((element) => {
      element.addEventListener(eventType, action, option);
    });
  }

  checkValidation(options) {
    console.log(options);


  }




}

*/



