
import parseTable from "./parseTable.js";
import parseJobs from "./parseJobs.js";
import parseFlats from "./parseFlats.js";
import { modalNotifier, moveProgressBar } from "./evts.js";
import editConf from "./editConf.js";


function loadTable(table) {
  document.getElementById("mainTitle").innerHTML = "selected table: "+table.replace(/_/g, " ");
  activeState.loadedtable = table;

  document.getElementById("navMob").className = document
    .getElementById("navMob")
    .className.replace(" w3-show", "");

  var xhttp = new XMLHttpRequest(); 
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      let resp;
      try {
        resp = JSON.parse(this.responseText);
      } catch {
        console.log(this.responseText);
      } finally {
        parseTable(resp);
      }
      
    }
  };
  xhttp.open("GET", "php/index.php/dbRead/" + table, true);
  xhttp.send();
}

function loadNewArticles(type = 'jobs') {
  activeState.loadedtable = 'soup';

  if (window.location.href.indexOf('flats') != -1) type = 'flats';
  let reqUrl;
  switch(type) {
    case 'jobs':
      reqUrl = "php/index.php/soup/quick";
      //document.getElementById("siteTitle").innerHTML = "Jobs";
      break;
    case 'flats':
      reqUrl = "php/index.php/soup/quick/flats";
      //document.getElementById("siteTitle").innerHTML = "Flats";
      break;
    default:
      reqUrl = "php/index.php/soup/quick";
      //document.getElementById("siteTitle").innerHTML = "Jobs";
  }



  document.getElementById("navMob").className = document
    .getElementById("navMob")
    .className.replace(" w3-show", "");


    //parseArticles('resp');
    //return

  modalNotifier('\
    fetching new articles \
    <div class="w3-flat-silver"> \
    <div id="loadingNewArticlesProgress" class="w3-container w3-flat-nephritis" style="height: 24px; width: 0%"></div> \
    </div> \
  ', 0, false);
  moveProgressBar(35);


  var xhttp = new XMLHttpRequest(); 
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      let resp;
      try {
        resp = JSON.parse(this.responseText);
      } catch (e) {
        modalNotifier('<i class="fa fa-exclamation-triangle" style="font-size: 1.3em"></i> <b> Error:</b> Could not get data from crawler', 0, false);
        return;
      }


      window.activeState['articles'] = resp;
      if (type == 'jobs') parseJobs(resp);
      if (type == 'flats') pagination(1, resp, parseFlats);
      
    }
  };
  xhttp.open("GET", reqUrl, true);
  xhttp.send();

}


function loadNavBar() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
      let res = JSON.parse(this.responseText);
      let divMob = document.getElementById("navMob");
      for (let x in res) {
        let aMob = document.createElement("a");

        aMob.setAttribute("href", "#");
        aMob.setAttribute("data-table", res[x][0]);
        aMob.classList.add("w3-bar-item", "w3-button", "w3-padding-large");
        aMob.innerHTML = res[x][0];

        divMob.appendChild(aMob);
      }
      let createEntry = document.createElement("a");
      createEntry.setAttribute("href", "#");
      createEntry.setAttribute("data-table", "createNew");
      createEntry.classList.add("w3-bar-item", "w3-button", "w3-padding-large");
      createEntry.innerHTML = "Edit Configuration";

      divMob.appendChild(createEntry);
      divMob.addEventListener("click", (e) => {
        if (e.target && e.target.matches("a.w3-bar-item")) {
          let table = e.target.dataset.table;
          if (table == "createNew") {
            editConf();
            return;
          }
          loadTable(table);
        }
      });
      loadNewArticles();
    }
  };
  xhttp.open("GET", "php/index.php/dbRead/tables", true);
  xhttp.send();
}

function loadArticles(page = 1) {
  let articles = window.activeState['articles'];
  window.activeState['currentPage'] = page;

  if (articles == '') {
    loadNewArticles(type);
  }

  if (window.location.href.indexOf('flats') != -1) pagination(page, articles, parseFlats);
  if (window.location.href.indexOf('jobs') != -1) pagination(page, articles, parseJobs);

}

function pagination(currentPage, articles, callBack) {
  //const queryString = window.location.search;
  //const urlParams = new URLSearchParams(queryString);
  //let currentPage = urlParams.get('page');

  let articleKeys = Object.keys(articles);

  if (currentPage == null || currentPage == '') {
    currentPage = 1;
  }
  let itemsAmount = 10;
  let itemsTotal = articleKeys.length;
  let pagesTotal = Math.floor(itemsTotal / itemsAmount);
  let pagedArticles = {};

  let loopEnd;
  let loopStart;
  if (currentPage == 1) {
    loopEnd = itemsAmount;
    loopStart = 0;
  } else {
    loopEnd = currentPage*itemsAmount;
    loopStart = (currentPage-1)*itemsAmount;
  }


  for (let i = loopStart; i < loopEnd; i++) {
    let id = articleKeys[i];
    pagedArticles[id] = articles[id];
  }

  //setup page button
  let pageDiv = document.getElementById('pagination');
  pageDiv.innerHTML = '';

  //if (screen.width < 993) {
  if (true) {
    let pageBtn = document.createElement('span');
    pageBtn.id = 'pageButton'
    pageBtn.classList.add("w3-button", "w3-large", "w3-flat-asbestos");
    pageBtn.innerText = 'Next';
    pageBtn.addEventListener("click", () => {
      window.scrollTo(0, 0)
      loadArticles(currentPage+1)
    });
    pageDiv.appendChild(pageBtn);
  } else {
    let div = document.createElement('div');

    let pageCount = currentPage+1;
    let a = document.createElement('a');
    a.href = '#';
    a.innerHTML = '&laquo;';
    a.classList.add("w3-button", "w3-large", "w3-hover-grey");
    div.appendChild(a);
    
    for (let i = 0; i < 4; i++) {
      let a = document.createElement('a');
      a.href = '#';
      a.innerText = pageCount;
      a.classList.add("w3-button", "w3-large", "w3-hover-grey");
      div.appendChild(a);
      pageCount++;
    }

    a = document.createElement('a');
    a.href = '#';
    a.innerHTML = '&raquo;';
    a.classList.add("w3-button", "w3-large", "w3-hover-grey");
    div.appendChild(a);

    pageDiv.appendChild(div);
    pageDiv.addEventListener("click", (e) => {
      if (e.target && e.target.matches("a.w3-button")) {
        let page = e.target.innerHTML;
        switch(page) {
          case '&raquo;':
            loadArticles(window.activeState['currentPage']+1);
            break;
          case '&laquo;':
            loadArticles(window.activeState['currentPage']-1);
            break;
          default:
            loadArticles(page);
        }
      }
    });
    
  }

  callBack(pagedArticles);
}


export {
  loadTable,
  loadNavBar,
  loadArticles
};
