package org.josast.EntrySat.app;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

import org.josast.kaikai.generated.FrameTlmEntrySat;
import org.josast.kaikai.generated.FrameTlmEntrySat.Ax25Frame;
import org.josast.kaikai.generated.FrameTlmEntrySat.UiFrameTlmEntrySat;

import io.kaitai.struct.ByteBufferKaitaiStream;

public class DecodeEntrySatFile {
	private static final String Version = "0.01";
	Options options = new Options();
	HelpFormatter formatter = new HelpFormatter();
	private BufferedReader lecteurAvecBuffer;
	private String ligne;

	public DecodeEntrySatFile() {

		// automatically generate the help statement

		// create Options object

		// add File option
		options.addOption("v", "verbose", false, "display information during the process");
		options.addOption("V", "Version", false, Version);
		Option FileOption = Option.builder("f").argName("file").hasArg().desc("Telemery file  ").build();
		options.addOption(FileOption);
		formatter.printHelp("DecodeTLM", options);

	}

	public void execute(String[] args) {
		CommandLineParser cmdLineParser = new DefaultParser();
		CommandLine commandLineGlobal;
		try {
			commandLineGlobal = cmdLineParser.parse(options, args);
			if (commandLineGlobal.hasOption("f")) {
				System.out.println("file to extract : " + commandLineGlobal.getOptionValue("f"));

				openFile(commandLineGlobal.getOptionValue("f"));
				readFile();

//				FrameTlmEntrySat frame;
//				try {
//					frame = FrameTlmEntrySat.fromFile(commandLineGlobal.getOptionValue("f"));
//					Telemetry tlm = new Telemetry();
//					tlm.setValue(frame.frameTlmEntrySat());
//
//					System.out.println(tlm.toStringHeader());
//					System.out.println(tlm.afficheTLM());
//
//					System.out.println(tlm.getValueDecoded(Telemetry.SID));
//					System.out.println(tlm.getValueDecoded(Telemetry.EPS_VBATT));
//
//				} catch (IOException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}

			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void openFile(String file) {
		try {
			lecteurAvecBuffer = new BufferedReader(new FileReader(file));
		} catch (FileNotFoundException exc) {
			System.out.println("Erreur d'ouverture");
		}
	}

	public void readFile() {
		boolean first = false;
		Date dateref = null;
		try {
			while ((ligne = lecteurAvecBuffer.readLine()) != null) {
				// System.out.println(ligne);
				String[] result1 = ligne.split("=");
				String[] date = result1[1].split("]");
				String[] trame = result1[2].split("]");

				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("E MMM dd hh:mm:ss z yyyy", Locale.ENGLISH);

				System.out.println("date : " + date[0] + " - Trame " + trame[0]);
				Date date2 = null;
				try {
					date2 = simpleDateFormat.parse(date[0]);
				} catch (java.text.ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (!first) {
					dateref = date2;
					first = true;
				} else {
					System.out.println((date2.getTime() - dateref.getTime()) / 1000);
				}
				byte[] tlm = hexStringToByteArray(trame[0]);
				FrameTlmEntrySat frame = new FrameTlmEntrySat(new ByteBufferKaitaiStream(tlm));
				Ax25Frame ax = frame.frameTlmEntrySat();
// 			System.out.println(ax.ax25Header().destSsidRaw());
// 			System.out.println(ax.ax25Header().srcSsidRaw());
				System.out.println(ax.ax25Header().destCallsignRaw().destCallsignRor().destCallsign());
				System.out.println(ax.ax25Header().srcCallsignRaw().srcCallsignRor().srcCallsign());

				if (ax.ax25Header().destCallsignRaw().destCallsignRor().destCallsign().compareTo("F6KTA ") == 0) {
//			System.out.println(ax.ax25Header().ctl());
					UiFrameTlmEntrySat Ui = (UiFrameTlmEntrySat) ax.payload();
//			System.out.println(Ui.packetheader().version());
//			System.out.println(Ui.packetheader().packetType());
//			System.out.println(Ui.packetheader().packetFlag());
//			System.out.println(Ui.packetheader().packetApid());
//			System.out.println(Ui.packetheader().sequenceControl());
//			System.out.println(Ui.packetheader().packetLenght());
					System.out.println("SID  : " + Ui.telemetryData().sid());
					if (Ui.telemetryData().sid() == 1) {
						System.err.println("SID valeur 4 ");
						System.exit(0);
					}
//			System.out.println("battTemp : " + Ui.telemetryData().battTemp());
//			System.out.println("eps33VCurrent : " + Ui.telemetryData().eps33VCurrent());
//			System.out.println("eps5VCurrent : " + Ui.telemetryData().eps5VCurrent());
//			System.out.println("epsBattVcurrent : " + Ui.telemetryData().epsBattVcurrent());
//			System.out.println("epsTemp : " + Ui.telemetryData().epsTemp());
//			System.out.println("trxTemp : " + Ui.telemetryData().trxTemp());

				} else {
					System.out.println("SID  :");
				}
			}
		}

		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void closeFile() {
		try {
			lecteurAvecBuffer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static byte[] hexStringToByteArray(String s) {
		byte[] b = new byte[s.length() / 2];
		for (int i = 0; i < b.length; i++) {
			int index = i * 2;
			int v = Integer.parseInt(s.substring(index, index + 2), 16);
			b[i] = (byte) v;
		}
		return b;
	}

	public static void main(String[] args) {
		DecodeEntrySatFile decode = new DecodeEntrySatFile();
		decode.execute(args);
	}
}
