package org.josast.app.amicalsat.cli.option;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Logger;

import org.josast.AX25.generated.Ax25frames;
import org.josast.ModuleSoundModem.SoundModemClient;
import org.josast.amicalsat.Frame;
import org.josast.amicalsat.FrameFactory;
import org.josast.amicalsat.generated.FrameTlmAmicalsat;
import org.josast.app.amicalsat.cli.AmicalsatCliConf;

import io.kaitai.struct.ByteBufferKaitaiStream;

public class ReceiveDataCmd implements Cmd {

	private Logger log = Logger.getLogger(getClass().getName());
	private SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd-HHmmss");

	@Override
	public void excute() {

		AmicalsatCliConf conf = AmicalsatCliConf.getInstance();
		FrameFactory ff = new FrameFactory();
		SoundModemClient sm = new SoundModemClient(conf.getConfigurationFile());
		if (!sm.isOpen()) {
			System.out.println("Connection to modem failed");
		} else {
			System.out.println("Connected to modem");
			while (sm.isOpen()) {

				byte[] temp = sm.receivedRawData();
				
			
				
				
				try {
					FrameTlmAmicalsat cube = new FrameTlmAmicalsat(new ByteBufferKaitaiStream(temp));
//AX25
					Ax25frames ax25 = new Ax25frames(new ByteBufferKaitaiStream(temp));
					byte [] info = ax25.ax25Frame().ax25Info();
					System.out.println(new String (info,StandardCharsets.UTF_8));
					
					
					String tlmArea = cube.frameTlmEntrySat().payload().tlmArea();
					String typeFrame = cube.frameTlmEntrySat().payload().tlmType();
					Frame fm = ff.creerFrame(tlmArea, typeFrame);
					fm.setUp(cube);

					Date aujourdhui = new Date();
					String receiveddate = formater.format(aujourdhui);

					System.out.println(receiveddate + " : " + fm.toStringHeader());
					System.out.println(fm.toString());
					if (conf.isGenerateTextualOutputFile()) {
						try {
							Files.writeString(conf.getRealTextualFilePath(), receiveddate, StandardOpenOption.APPEND);
							Files.writeString(conf.getRealTextualFilePath(), fm.toStringHeader(),
									StandardOpenOption.APPEND);
							Files.writeString(conf.getRealTextualFilePath(), fm.toString() + "\r\n",
									StandardOpenOption.APPEND);
						} catch (IOException e) {
							log.severe(e.toString());
						}
					}
				} catch (Exception e) {
					log.severe("Data input received not decoded " + e.toString());
				}

			}

			System.out.println("Connection closed");
		}

	}
}
