const PER_PAGE = 45;

function initializeReadingListPage(){
  if ( getCurrentPage("reading_list_items-index") && checkUserLoggedIn() ) {
    var publicSearchKey = '<%= ALGOLIASEARCH_PUBLIC_SEARCH_ONLY_KEY %>'
    client = algoliasearch('<%= ApplicationConfig["ALGOLIASEARCH_APPLICATION_ID"] %>', publicSearchKey);
    readinglistIndex = client.initIndex('ordered_articles_<%= Rails.env %>');
    commentsIndex = client.initIndex('ordered_comments_<%= Rails.env %>');
    var params = getQueryParams(document.location.search);
    document.getElementById('substories').dataset.tabs = '{"v": "'+(params.v || '')+'", "t": "'+(params.t || '')+'" }'
    postCommentFilter();
    getArticlesTags();
    document.getElementById("load-more-cta").onclick = function(event) {
      event.target.classList.remove("showing");
      var nextNumber = document.getElementsByClassName('single-article').length + PER_PAGE;
      getArticles(currentTag(), nextNumber);
    }
  }
}

function currentTag() {
  var tabsObj = JSON.parse(substories.dataset.tabs);
  return (tabsObj["t"] || "");
}

function getArticlesTags(){
  var user = userData();
  var algoliaIds = user.reading_list_ids.map(function(id){return "articles-"+id});
  var tags = {}

  readinglistIndex.getObjects(algoliaIds, function(err, content) {
    content.results.forEach(function(story, i){
      if (story) {
        story.tag_list.forEach(function(tag){
          if (tags[tag]){
            tags[tag] = tags[tag]+1;
          } else {
            tags[tag] = 1;
          }
        })
      }
    })
    renderTags(tags);
    document.getElementById('tag-filter-widget').setAttribute('data-tags', JSON.stringify(tags));
    initializeReadingListIcons();
  });
}

function tagsCounts() {
  var dataTags = document.getElementById('tag-filter-widget').getAttribute('data-tags');
  return dataTags ? JSON.parse(dataTags) : {};
}

function getArticles(tag, num = PER_PAGE){
    var user = userData();
    var substoriesDiv = document.getElementById("substories");
    var algoliaIds = user.reading_list_ids.slice(0, 999).map(function(id){return "articles-"+id});
    var resultDivs = []
    var showMore = false;
    var tagSpecified = (tag != "");

    readinglistIndex.getObjects(algoliaIds, function(err, content) {
      if (tagSpecified){
        var results = content.results;
        for (var i in results) {
          if (resultDivs.length >= num) {
            break;
          }
          if (results[i] && results[i].tag_list.indexOf(tag) > -1) {
            resultDivs.push(buildArticleHTML(results[i]));
          }
        }
        showMore = tagsCounts()[tag] > num;
      }
      else {
        content.results.slice(0, num).forEach(function(story, i){
          if (story) {
            resultDivs.push(buildArticleHTML(story));
          }
        })
        showMore = num < content.results.length;
      }

      substoriesDiv.innerHTML = resultDivs.join("");
      if ( resultDivs.length == 0) {
        var message = "<div style='text-align:left;margin-top:20px;'>This is where to find your bookmarked posts, but it looks like you have not bookmarked anything.</div>"
        substoriesDiv.innerHTML = message;
      }

      var showMoreButton = document.getElementById("load-more-cta");
      showMore ? showMoreButton.classList.add("showing") : showMoreButton.classList.remove("showing")
    });
}

function getComments(){
  var user = userData();
  var algoliaIds = user.reading_list_ids.map(function(id){return "commentable_Article_"+id});
  var substories = document.getElementById("substories");
  var tabsObj = JSON.parse(substories.dataset.tabs);
  commentsIndex.search("*", {
      hitsPerPage: PER_PAGE,
      attributesToHighlight: [],
      tagFilters: [algoliaIds,tabsObj["t"]],
  })
  .then(function searchDone(content) {
    var substoriesDiv = document.getElementById("substories");
    var resultDivs = []
    content.hits.forEach(function(comment){
      var aboveDiv = ""
        aboveDiv = aboveDiv + '<div class="comment-view-parent comment-view-commentable"><a href="'+comment.commentable.path+'">Re: '+comment.commentable.title+'</a></div>'
      if (comment.parent_path) {
        aboveDiv = aboveDiv + '<div class="comment-view-parent"><a href="'+comment.root_path+'">VIEW COMMENT TREE</a></div>'
      }
      resultDivs.push(aboveDiv+buildCommentHTML(comment));
    });
    substoriesDiv.innerHTML = '<div class="comment-trees"><h2>Recent Comment Activity</h2>'+resultDivs.join("<br/>")+'</div>';
    initializeCommentDropdown();
    initializeCommentsPage();
  });
}

function renderTags(tags){
  var sortedTags = [];
  for (var tag in tags) {
      sortedTags.push([tag, tags[tag]]);
  }
  sortedTags.sort(function(a, b) {
      return b[1] - a[1];
  });
  var tagDivs = []
  sortedTags.forEach(function(tag){
    var html = '<button class="query-filter-button query-tag-filter-button" data-tag="'+tag[0]+'">#'+tag[0]+' ('+tag[1]+')</button>'
    tagDivs.push(html)
  })
  document.getElementById("tag-filters").innerHTML = tagDivs.join("");
  var params = getQueryParams(document.location.search);
  var tag = filterXSS(params.t || "");
  tagFilters(tag);
}

function getQueryParams(qs) {
  qs = qs.split('+').join(' ');

  var params = {},
      tokens,
      re = /[?&]?([^=]+)=([^&]*)/g;

  while (tokens = re.exec(qs)) {
      params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
  }

  return params;
}

function tagFilters(tag){
  var substories = document.getElementById('substories');
  var filterButts = document.getElementsByClassName("query-tag-filter-button");
  for(var i = 0; i < filterButts.length; i++) {
    filterButts[i].classList.remove("selected");
    if (tag == filterButts[i].dataset.tag){
      filterButts[i].classList.add("selected");
    }
    filterButts[i].onclick = function(e){
      var tag = e.target.dataset.tag;
      window.scrollTo(0, 0);
      var className = e.target.className;
      var tabsObj = JSON.parse(substories.dataset.tabs);
      for(var i = 0; i < filterButts.length; i++) {
        filterButts[i].classList.remove("selected");
      }
      if (className.indexOf("selected") == -1 ) {
        e.target.classList.add("selected");
        assignTab(tabsObj, "t", tag)
        getStories();
      } else{
        assignTab(tabsObj, "t", "")
        getStories();
      }
    }
  }
}

function postCommentFilter(){
  var substories = document.getElementById('substories');
  var tabsObj = JSON.parse(substories.dataset.tabs);
  getStories()
  var filterButts = document.getElementsByClassName("query-type-filter-button");
  for(var i = 0; i < filterButts.length; i++) {
    filterButts[i].classList.remove("selected");
    if ((tabsObj["v"] || "posts") === filterButts[i].dataset.type){
      filterButts[i].classList.add("selected");
    }
    filterButts[i].onclick = function(e){
      for(var i = 0; i < filterButts.length; i++) {
        filterButts[i].classList.remove("selected");
      }
      var tabsObj = JSON.parse(substories.dataset.tabs);
      assignTab(tabsObj, "v", e.target.dataset.type);
      e.target.classList.add("selected");
      getStories()
    }
  }
}

function getStories(){
  var substories = document.getElementById('substories');
  var tabsObj = JSON.parse(substories.dataset.tabs);
  if (tabsObj["v"] == "comments") {
    getComments(tabsObj["t"] || "");
  } else {
    getArticles(tabsObj["t"] || "", PER_PAGE);
  }
}

function assignTab(obj, tab, value) {
  obj[tab] = value
  substories.dataset.tabs = JSON.stringify(obj);
  window.history.replaceState(null, null, "/readinglist"+urlParams(obj));
  return obj
}

function urlParams(obj){
  if (obj["v"].length > 0 && obj["t"].length > 0) {
    return "?v="+obj["v"]+"&t="+obj["t"]
  } else if (obj["v"].length > 0) {
    return "?v="+obj["v"]
  } else if (obj["t"].length > 0) {
    return "?t="+obj["t"]
  } else {
    return ""
  }
}
