#include <cstdio>
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>

#include "json.hpp"
#include "priorityqueue.h"

int main(int argc, char** argv) {
  // read JSON file and store in jsonObject
  std::ifstream file;
  file.open(argv[1]);
  nlohmann::json jsonObject;
  // Store the contents filename into jsonObject
  if (file.is_open()) {
    file >> jsonObject;
  }

  std::string sampleName;     // Sample key name to iterate
  nlohmann::json outputJSON;  // output JSON file
  int currValue = 0;          // current key value

  int n = jsonObject["metadata"]["arraySize"];

  std::vector<int> A(n, 0);

  class PriorityQueue sampleHeap;
  sampleHeap.initiateHeap(n);

  for (auto itr = jsonObject.begin(); itr != jsonObject.end(); ++itr) {
    sampleName = itr.key();

    if (sampleName != "metadata") {
      nlohmann::json topOfHeap;

      for (auto arrayItr = jsonObject[sampleName].begin(); arrayItr != jsonObject[sampleName].end(); ++arrayItr) {
        // insert each array element into heap
        currValue = *arrayItr;
        sampleHeap.insert(currValue);
      }

      // insert heap top key values into an array backwards to sort from min to max
      for (int i = n - 1; i >= 0; i--) {
        A[i] = sampleHeap.returnMax();
        sampleHeap.removeMax();
      }

      // convert the new array into a JSON object
      for (int j = 0; j <= n - 1; j++) {
        // adding values directly to JSON object
        topOfHeap.push_back(A[j]);
      }
      outputJSON[sampleName] = topOfHeap;
    }
  }
  outputJSON["metadata"]["arraySize"] = n;
  outputJSON["metadata"]["numSamples"] = jsonObject["metadata"]["numSamples"];
  std::cout << outputJSON << std::endl;

  // clean up memory
  file.close();
  sampleHeap.deleteHeap();
  return 0;
}
