package com.elphel.imagej.ims;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
//import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
//import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;

public class UasLogReader {
	public UasLogReader(String filePath) throws JSONException {
		String [] filed_to_print = {
				"timestamp",
				"distanceFromHome",
				"gps_lat",
                "gps_lon",
                "gps_altitude",
                "homeLatitude",
                "homeLongitude"};
    	StringBuffer sb = new StringBuffer();
    	sb.append(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime())+"\n");
        try {
            String jsonString = new String(Files.readAllBytes(Paths.get(filePath)));
            JSONObject logData = new JSONObject(jsonString);
            /*
                    647.8000000000103,
                    40.36068344116211,
                    -112.02062225341797,

             * 
            String fancy_data = logData.toString(4); 
            try {
                Path path = Paths.get(filePath+".txt");
                Files.write(path, fancy_data.getBytes(StandardCharsets.UTF_8));
                System.out.println("String successfully written to file: " + path);
            } catch (IOException e) {
                System.err.println("An error occurred while writing to the file: " + e.getMessage());
            }
             */
            JSONArray flight_logging_items = logData.getJSONObject("exchange").getJSONObject("message").getJSONObject("flight_logging").getJSONArray("flight_logging_items");
            JSONArray flight_logging_keys =  logData.getJSONObject("exchange").getJSONObject("message").getJSONObject("flight_logging").getJSONArray("flight_logging_keys");
//            String [] log_keys = new String [flight_logging_keys.length()];
            HashMap<String, Integer> log_indices = new HashMap<String, Integer>();
            for (int i = 0; i < flight_logging_keys.length(); i++) {
            	log_indices.put(flight_logging_keys.getString(i), i);
            }
            int [] indices =  new int[filed_to_print.length];
            for (int i = 0; i < filed_to_print.length; i++) {
            	indices[i] = log_indices.get(filed_to_print[i]);	
            }
            sb.append("index\t");
            for (int i = 0; i < filed_to_print.length; i++) {
                sb.append(filed_to_print[i]);
                sb.append((i < (filed_to_print.length - 1))?"\t":"\n");
            }
            for (int indx = 0; indx < flight_logging_items.length(); indx++) {
            	sb.append(indx+"\t");
            	JSONArray log_line =flight_logging_items.getJSONArray(indx);
                for (int i = 0; i < filed_to_print.length; i++) {
                    sb.append(log_line.get(indices[i]));
                    sb.append((i < (filed_to_print.length - 1))?"\t":"\n");
                }            	
            }
//            System.out.println("flight_logging_keys.length()="+flight_logging_keys.length());
//            JSONObject logData_exchange = (JSONObject) logData.getJSONObject("exchange");
            // Accessing data
//            String droneId = logData.getString("droneId");
            /*
            double latitude = logData.getJSONObject("location").getDouble("latitude");
            double longitude = logData.getJSONObject("location").getDouble("longitude");

//            System.out.println("Drone ID: " + droneId);
            System.out.println("Latitude: " + latitude);
             System.out.println("Longitude: " + longitude);
*/
        } catch (IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
        }
		try {
			BufferedWriter out = new BufferedWriter(
					new FileWriter(filePath+".csv", true));
			out.write(sb.toString());
			out.close();
//			return; //  true;
        } catch (IOException e) {
            // Display message when exception occurs
            System.out.println("exception occurred" + e);
            return; //  false;
        }
        
        return;
        /*
            "flight_logging_keys": [
                "timestamp",
                "gps_lat",
                "gps_lon",
                "gps_altitude",
                "speed_vx",
                "speed_vy",
                "zSpeed",
                "dronePitch",
                "droneRoll",
                "droneYaw",
                "mLeftHorizontal",
                "mLeftVertical",
                "mRightHorizontal",
                "mRightVertical",
                "batteryCapacityPercentage",
                "phoneHeading",
                "currentJourney",
                "distanceFromHome",
                "battery_voltage",
                "currentElectricity",
                "currentCurrent",
                "visionWarning",
                "visionExtWarning",
                "visionErrorCode",
                "radarInfoTimeStamp",
                "frontRadarInfo",
                "rearRadarInfo",
                "leftRadarInfo",
                "rightRadarInfo",
                "topRadarInfo",
                "bottomRadarInfo",
                "alertArry",
                "remoteLatitude",
                "remoteLongitude",
                "flightMode",
                "gimbalPitch",
                "gimbalRoll",
                "gimbalYaw",
                "gpsSignalLevel",
                "rcRSSI",
                "rcModeState",
                "rcPowerState",
                "rcTakeOffState",
                "rcHomeState",
                "rcHoverState",
                "cameraMode",
                "mMode",
                "timeLeft",
                "homeLatitude",
                "homeLongitude",
                "satelliteCount",
                "designedVolume",
                "fullChargeVolume",
                "batteryTemperature",
                "remainPowerPercent",
                "numberOfDischarge",
                "cellCount",
                "maxFlightAltitude",
                "voltageOfCells",
                "goHomeAltitude",
                "beginnerModeEnable",
                "lowBatteryWarningThreshold",
                "seriousBatteryWarningThreshold",
                "maxFlightRadius",
                "maxFlightHorizontalSpeed",
                "obstacleAvoidanceEnable",
                "radarEnable",
                "gearMode",
                "backTime",
                "imageName",
                "imagePath"
            ],

         */
	}
	
}
