package JSON_Unpack;

import Credentials.UserCredentials;
import Files.WriteFile;
import HttpCall.HttpGet;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;

///url/sensors/id/read

public class ReadSensors4Partner {

  public ArrayList<String> FetchSensor4Box(String companyName, String token)
    throws Exception {
    switch (companyName) {
      case "Germes":
        return SensorRead("Germes", token);
      case "Heufs":
        return SensorRead("Heufs", token);
      case "Jacobs":
        return SensorRead("Jacobs", token);
      case "Nica":
        return SensorRead("Nica", token);
    }
    return null;
  }

  protected ArrayList<String> SensorRead(String cName, String token)
    throws Exception {
    UserCredentials userCredentials = new UserCredentials();
    HttpGet httpCall = new HttpGet();
    WriteFile writingIntoFile = new WriteFile();

    String baseURL = userCredentials.getBaseURL();
    String devUrl = userCredentials.getDevUrl();
    String homeRoot = UserCredentials.getHomeRoot();

    ArrayList<String> list = new ArrayList<String>();
    char par = '"';

    BoxCall4Partner boxCall4Partner = new BoxCall4Partner();
    ArrayList<String> outputBox = boxCall4Partner.FetchBox(cName, token);
    for (int i = 0; i < outputBox.size(); i++) {
      JSONArray jsonArray = new JSONArray(outputBox.get(i));
      for (int j = 0; j < jsonArray.length(); j++) {
        JSONObject jsonobject = jsonArray.getJSONObject(j);
        String jsonID = jsonobject.getString("id");
        String jsonTag = jsonobject.getString("tag");
        String deviceID = jsonobject.getString("deviceId");
        String finalTag =
          "," +
          par +
          "deviceId" +
          par +
          ":" +
          deviceID +
          "," +
          par +
          "sensorTag" +
          par +
          ":" +
          jsonTag +
          "}]";

        String sensorOutput = httpCall.HttpGetCall(
          devUrl + "sensors/" + jsonID + "/read" + "?access_token=" + token,
          token
        );
        if (sensorOutput.contains("error")) {
          System.out.println(sensorOutput);
        } else {
          String modification = sensorOutput.replace("}]", "");
          String finalSensorOutput = modification + finalTag;
          list.add(finalSensorOutput);

          writingIntoFile.WriteFile(
            homeRoot + jsonID + ".json",
            sensorOutput + jsonTag + "," + deviceID
          );
        }
      }
    }

    return list;
  }
}
