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

import java.io.IOException;
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.ModuleSoundModem.SoundModemClient;
import org.josast.amicalsat.Frame;
import org.josast.amicalsat.FrameFactory;
import org.josast.amicalsat.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();

				FrameTlmAmicalsat cube = new FrameTlmAmicalsat(new ByteBufferKaitaiStream(temp));
				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());
					}
				}

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

	}
}
