#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 heapOp;         // heap operation to iterate
  std::string currOp;         // operation name
  int key;                    // node key given for each operation
  int newKey;                 // node key given for each operation

  // obtain max heap size from JSON input file and initialize priorityqueue heap with this number
  int n = jsonObject["metadata"]["maxHeapSize"];
  int opInHeap = jsonObject["metadata"]["numOperations"];
  class PriorityQueue opHeap;
  opHeap.initiateHeap(n);
  // initialize vector *** may not be needed ***
  std::vector<int> A(n, 0);

  // need to iterate through each operation
  for (auto itr = jsonObject.begin(); itr != jsonObject.end(); ++itr) {
    heapOp = itr.key();

    if (heapOp != "metadata") {
      // get the operation name to be performed
      currOp = jsonObject[heapOp]["operation"];

      // perform correct operation gotten from JSON Op object
      if (currOp == "insert") {
        key = jsonObject[heapOp]["key"];
        opHeap.insert(key);

      } else if (currOp == "change") {
        key = jsonObject[heapOp]["key"];
        newKey = jsonObject[heapOp]["newKey"];
        opHeap.change(key, newKey);

      } else if (currOp == "removeMax") {
        opHeap.removeMax();

      } else if (currOp == "removeKey") {
        key = jsonObject[heapOp]["key"];
        opHeap.removeKey(key);

      }
    }
  }

  // print tree using JSON formatting
  opHeap.printJSONTree(n, opInHeap);

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