class sCal {
  constructor(selector){
    let _this = this;
    _this.calendar = document.querySelector(selector);
    _this.monthRow = ['1월','2월','3월','4월','5월','6월','7월','8월','9월','10월','11월','12월'];
    _this.weekRow = ['일','월','화','수','목','금','토'];
    _this.today = new Date();
    _this.toyear = new Date().getFullYear();
    _this.tomon = new Date().getMonth()+1;
    // _this.inDates = []; //{날짜:데이터 형식...일단 그렇게...아니 배열로}
    // _this.outDates = []; //{날짜:데이터 형식...일단 그렇게... 아니 배열로}
  }

  cellDate (tgt, dayinfo) {
    return dayinfo.date;
  };
  cellHtml (tgt, dayinfo) {
    return "";
  };

  enablefunc () {return true;};
  combinefunc () {return true;};
  makeCal (year, mon, caldata) {
    let _this = this;

    year = year || _this.toyear;
    mon = mon || _this.tomon;
    _this.toyear = year;
    _this.tomon = mon;
    if( typeof _this.cellDate != "function" ){
      let data = _this.cellDate;
      _this.cellDate = function(){ return data; }
    }
    if( typeof _this.cellHtml != "function" ){
      let data = _this.cellHtml;
      _this.cellHtml = function(){ return data; }
    }

    // _this.inDates = _this.inDates.map(v => { let vsp = v.split("-"); return vsp[0]+'-'+('0'+vsp[1]).slice(-2)+'-'+('0'+vsp[2]).slice(-2) });
    // _this.outDates = _this.outDates.map(v => { let vsp = v.split("-"); return vsp[0]+'-'+('0'+vsp[1]).slice(-2)+'-'+('0'+vsp[2]).slice(-2) });

    let yearSelect = document.createElement("select"),
    monSelect = document.createElement("select"),
    calTitle = document.createElement("div"),
    selDiv = document.createElement("div");
    yearSelect.id = "selyear";
    monSelect.id = "selmon";
    calTitle.id = "caltitle";
    yearSelect.classList.add("selYear");
    monSelect.classList.add("selMon");
    calTitle.classList.add("calTitle");
    selDiv.classList.add("selDiv");
    selDiv.classList.add("selDiv");

    for( let a=_this.toyear - 10 ; a<=_this.toyear + 10 ; a++ ){
      let opt = document.createElement("option");
      opt.value = a;
      opt.text = a;
      yearSelect.appendChild(opt);
    }
    yearSelect.classList.add("form-control-sm");
    yearSelect.classList.add("w80");
    yearSelect.addEventListener("change",()=>_this.gotoCal(_this));

    for( let a=1 ; a<=12 ; a++ ){
      let opt = document.createElement("option");
      opt.value = a;
      opt.text = a;
      monSelect.appendChild(opt);
    }
    monSelect.classList.add("form-control-sm");
    yearSelect.classList.add("w40");
    monSelect.addEventListener("change",()=>_this.gotoCal(_this));

    let btnPrev1 = document.createElement("a");
    btnPrev1.innerHTML= "<i class='bi bi-arrow-left-circle'></i>";
    let btnPrev2 = btnPrev1.cloneNode(true);
    ['click','keypress'].forEach(evt => btnPrev1.addEventListener(evt, ()=>_this.prevCal(_this)));
    ['click','keypress'].forEach(evt => btnPrev2.addEventListener(evt, ()=>_this.prevCal(_this)));
    let btnNext1 = document.createElement("a");
    btnNext1.innerHTML= "<i class='bi bi-arrow-right-circle'></i>";
    let btnNext2 = btnNext1.cloneNode(true);
    ['click','keypress'].forEach(evt => btnNext1.addEventListener(evt, ()=>_this.nextCal(_this)));
    ['click','keypress'].forEach(evt => btnNext2.addEventListener(evt, ()=>_this.nextCal(_this)));
    let spanTitle = document.createElement("span");
    spanTitle.innerHTML = year +" / "+ ('0'+mon).slice(-2);

    calTitle.appendChild(btnPrev1);
    calTitle.appendChild(spanTitle);
    calTitle.appendChild(btnNext1);

    selDiv.appendChild(btnPrev2);
    selDiv.appendChild(yearSelect);
    selDiv.appendChild(monSelect);
    selDiv.appendChild(btnNext2);

    yearSelect.value = year;
    monSelect.value = mon;

    let sweek = new Date( year, mon-1 ).getDay(),
    dayInMon = 32 - new Date( year, mon-1, 32 ).getDate(),
    adweek = 6 - new Date( year, mon-1, dayInMon ).getDay(),
    fdate = dayInMon + adweek;

    let calTable = document.createElement("table"),
    thead = document.createElement("thead"),
    tbody = document.createElement("tbody"),
    thtr = document.createElement("tr");
    _this.weekRow.forEach(w=>{
      let week = document.createElement("th");
      week.innerHTML = w;
      thtr.append(week);
    });
    thead.append(thtr);
    calTable.classList.add("calTable");

    let date = 1;
    for( let a=0; a<6; a++ ) {
      let tr = document.createElement("tr");
      for( let b = 0; b < 7; b++ ) {
        let cell, cellText;
        if( a === 0 && b < sweek || date > dayInMon && date <= fdate ) {
          cell = document.createElement( "td" );
          cellText = document.createTextNode("");
          cell.appendChild(cellText);
          tr.appendChild(cell);
          if( date > dayInMon ) date++;
        }else if( date <= dayInMon ){
          let idv = year+(('0'+mon).slice(-2))+(('0'+date).slice(-2));
          cell = document.createElement("td");
          cell.id = "ymd"+idv;
          cell.setAttribute("data-date", ('0'+date).slice(-2));
          cell.setAttribute("data-mon", ('0'+mon).slice(-2));
          cell.setAttribute("data-year", year);
          cell.setAttribute("data-week", b);
          cell.classList.add("date-td");
          // _this.inDates.forEach(v => {
          //   let vd = v.split("-");
          //   if( (new Date(Number(vd[0]),Number(vd[1])-1,Number(vd[2]))).getTime() == (new Date(year, mon-1, date)).getTime() ){
          //     cell.classList.add("date-in");
          //   }
          // });
          // _this.outDates.forEach(v => {
          //   let vd = v.split("-");
          //   if( (new Date(Number(vd[0]),Number(vd[1])-1,Number(vd[2]))).getTime() == (new Date(year, mon-1, date)).getTime() ){
          //     cell.classList.add("date-out");
          //   }
          // });
          if( year === _this.today.getFullYear() && mon === (_this.today.getMonth()+1) && date === _this.today.getDate() ) {
            cell.classList.add("date-picker");
            cell.classList.add("selected");
          }
          cell.innerHTML = "<label class='calcls'>"+ _this.cellDate(_this, {year, mon, date}) +"</label><div class='caltext'>"+_this.cellHtml(_this, {year, mon, date, week:b, data:caldata[date]})+"</div>";

          // ['click','keypress'].forEach(evt=>{
          //   cell.addEventListener(evt, (e)=>{
          //     if( !_this.enablefunc() ){ //특정값 부재시 return;  옵션으로 조건 함수
          //       return false;
          //     }
          //
          //     if( cell.classList.contains("date-in") ){
          //       cell.classList.remove("date-in");
          //       _this.inDates = _this.inDates.filter( val => val != cell.dataset.year+"-"+cell.dataset.mon+"-"+ cell.dataset.date );
          //     }else{
          //       cell.classList.add("date-in");
          //       _this.inDates.push(cell.dataset.year+"-"+cell.dataset.mon+"-"+cell.dataset.date);
          //       _this.inDates = _this.inDates.sort( (a, b) => a > b ? 1 : -1 );
          //     }
          //
          //     _this.combinefunc(_this.inDates); //외부 실행 함수
          //   });
          // });
          tr.appendChild(cell);
          date++;
        }
      }
      tbody.appendChild(tr);
    }
    calTable.appendChild(thead);
    calTable.appendChild(tbody);
    _this.calendar.innerHTML = "";
    _this.calendar.appendChild(selDiv);
    //_this.calendar.appendChild(calTitle);
    _this.calendar.appendChild(calTable);
  };

  // nextCal (tgt) {
  //   let toyear = (tgt.tomon === 12) ? tgt.toyear + 1 : tgt.toyear,
  //   tomon = (tgt.tomon === 12) ? 1 : tgt.tomon + 1;
  //   tgt.makeCal(toyear, tomon);
  // };

  // prevCal (tgt) {
  //   let toyear = (tgt.tomon === 1) ? tgt.toyear - 1 : tgt.toyear,
  //   tomon = (tgt.tomon === 1) ? 12 : tgt.tomon - 1;
  //   tgt.makeCal(toyear, tomon);
  // };

  // gotoCal (tgt) {
  //   let toyear = parseInt(document.querySelector(".selYear").value),
  //   tomon = parseInt(document.querySelector(".selMon").value);
  //   tgt.makeCal(toyear, tomon);
  // };

  nextCal (tgt){
    let toyear = (tgt.tomon === 12) ? tgt.toyear + 1 : tgt.toyear,
    tomon = (tgt.tomon === 12) ? 1 : tgt.tomon + 1;
    loadSchedule('', toyear, tomon);
  }
  prevCal (tgt){
    let toyear = (tgt.tomon === 1) ? tgt.toyear - 1 : tgt.toyear,
    tomon = (tgt.tomon === 1) ? 12 : tgt.tomon - 1;
    loadSchedule('', toyear, tomon);
  }
  gotoCal (tgt) {
    let toyear = parseInt(document.querySelector(".selYear").value),
    tomon = parseInt(document.querySelector(".selMon").value);
    loadSchedule('', toyear, tomon);
  };
};