class Results {
  constructor(resultsJSON, resultsList , metaDataJSON) {
  this.resultsJSON = resultsJSON;
  this.resultsList = resultsList;
  this.metaDataJSON = metaDataJSON
  }

  clearAll() {
    this.resultsList.clear();
    this.resultsList.update();
    this.resultsJSON.init();
    this.metaDataJSON.init();
  }
}


class ResultsJSON {
  // Sets empty object structure. Also usefull to delete old results.
  // matchCount default is 0
  init(matchCount = 0) {
    this["matches"] = [];  // list of all c with lc and rc
    this["cpos_lookup"] = {};  // object contains all this key value pair
    this["text_lookup"] = {};  // same as above for all text ids
    this["match_count"] = matchCount;
  }

  // get query as string from form Element
  getQueryStr(queryFormElement) {
    // gets query
    let queryFormData;
    let queryStr;
    queryFormData = new FormData(queryFormElement);
    queryStr = queryFormData.get("query-form-query");
    this["query"] = queryStr;
  }

  // function creates a unique and safe filename for the download
  createDownloadFilename(suffix) {
    let today;
    let currentDate;
    let currentTime;
    let safeFilename;
    let resultFilename;
    // get and create metadata
    today = new Date();
    currentDate = `${today.getUTCFullYear()}` +
                  `-${(today.getUTCMonth() + 1)}` +
                  `-${today.getUTCDate()}`;
    currentTime = `${today.getUTCHours()}h` +
                  `${today.getUTCMinutes()}m` +
                  `${today.getUTCSeconds()}s`;
    safeFilename = this.query.replace(/[^a-z0-9_-]/gi, "_");
    resultFilename = `UTC-${currentDate}_${currentTime}_${safeFilename}_${suffix}`;
    return resultFilename
  }

  // Function to download data as Blob created from string
  // should be private but that is not yet a feature of javascript 08.04.2020
  download(downloadElement, dataStr, filename, type, filenameSlug) {
    console.log("Start Download!");
    let file;
    filename += filenameSlug;
    file = new Blob([dataStr], {type: type});
        var url = URL.createObjectURL(file);
        downloadElement.href = url;
        downloadElement.download = filename;
  }

  // function to download the results as JSON
  downloadJSONRessource(resultFilename, downloadData, downloadElement) {
    let dataStr;
    // stringify JSON object for json download
    // use tabs to save some space
    dataStr = JSON.stringify(downloadData, undefined, "\t");
    // start actual download
    this.download(downloadElement, dataStr, resultFilename, "text/json", ".json")
  }
}

class MetaDataJSON {
  // Sets empty object structure. Also usefull to delete old results.
  init() {
    this["corpus_name"] = "";
    this["corpus_description"] = "";
    this["corpus_creation_date"] = "";
    this["corpus_properties"] = "";
  }
}