package eu.hsrw.ias.ggd;

import Credentials.UserCredentials;
import Files.WriteFile;
import JSON_Unpack.ReadSensors4Partner;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONObject;

public class ApiCall {

  private static String token = "0";
  private static String oldId = "1";

  public static Greenhouse FetchDataFromApi() throws Exception {
    UserCredentials userCredentials = new UserCredentials();
    final String username = userCredentials.getUsername();
    final String password = userCredentials.getPassword();
    final String homeRoot = UserCredentials.getHomeRoot();
    String outputToken;
    WriteFile writingIntoFile = new WriteFile();
    Date now; // to display current time
    now = new Date();
    HashMap<String, Device> devices = new HashMap();

    if (token.equals(oldId)) {
      //do nothing
    } else {
      try {
        outputToken = SecurityToken.OnCallMethod(username, password);
        JSONObject obj = new JSONObject(outputToken);
        token = obj.getString("id");

        writingIntoFile.WriteFile(homeRoot + "securityToken.txt", token);
        oldId = token;
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    ReadSensors4Partner readSensors4Partner = new ReadSensors4Partner();
    ArrayList<String> outputValue =
      (readSensors4Partner.FetchSensor4Box("Nica", token));

    for (int i = 0; i < outputValue.size(); i++) {
      Device device;
      JSONArray sensorDatas = new JSONArray(outputValue.get(i));

      for (int j = 0; j < sensorDatas.length(); j++) { //15
        JSONObject sensorData = sensorDatas.getJSONObject(j);

        String deviceId = sensorData.getString("deviceId");

        double value = sensorData.getDouble("value");
        String sensorTag = sensorData.getString("sensorTag");
        String sensorId = sensorData.getString("sensorId");

        SensorData sd = new SensorData(sensorId, value, sensorTag);

        if (devices.containsKey(deviceId)) {
          device = devices.get(deviceId);
          device.addSensorData(sd);
        } else {
          device = new Device(deviceId);
          device.addSensorData(sd);
          devices.put(deviceId, device);
        }
      }
    }
    Greenhouse greenhouse = new Greenhouse();
    for (Device device : devices.values()) {
      greenhouse.addDevice(device);
    }
    return greenhouse;
  }
}
