package JSON_Unpack;

import Credentials.UserCredentials;
import Files.ReadFile;
import Files.WriteFile;
import HttpCall.HttpGet;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

// Get sensor from device for each partner
public class BoxCall4Partner {

    public ArrayList<String> FetchBox(String companyName, String token) throws Exception {

        switch (companyName) {
            case "Germes":
                return onCallMethod("Germes", token);
            case "Heufs":
                return onCallMethod("Heufs", token);
            case "Jacobs":
                return onCallMethod("Jacobs", token);
            case "Nica":
                return onCallMethod("Nica", token);
        }
        return null;
    }

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

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

        String outputGeneral = GeneralCall4AllDevices.FetchAll(token);
        JSONArray jsonarray = new JSONArray(outputGeneral);

        cName = readFile.ReadFromFile(homeRoot + cName + ".txt");
        ArrayList<String> listOfCompanyOutputs = new ArrayList<String>();

        String[] listOfCompanyDevices = cName.split(",");
        for (String companyExternalID : listOfCompanyDevices) {
            for (int i = 0; i < jsonarray.length(); i++) {
                JSONObject deviceFromCall = jsonarray.getJSONObject(i);
                String deviceExternalID = deviceFromCall.getString("externalId");

                if (companyExternalID.equals(deviceExternalID)) {
                    String backendID = deviceFromCall.getString("id");
//                    String deviceID = jsonobject.getString("deviceId");
                    String companyOutput = httpCall.HttpGetCall(devUrl + "devices/" + jsonID + "/sensors" + "?access_token=" + token, token);
                    listOfCompanyOutputs.add(companyOutput);
                    writingIntoFile.WriteFile(homeRoot + companyExternalID + ".json", companyOutput);

                }
            }
        }
        return listOfCompanyOutputs;
    }


}
