package gurux.dlms.server.example;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class ReformatBuffer {
    public String outputString;

    static int cutoffASCII = 10; // ASCII code of the character used for cut-off between received messages
    static String bufferReadToString = ""; // empty, but not null

    public static void parseByteArray(byte[] readBuffer) {
                String s = new String(readBuffer);
                bufferReadToString = bufferReadToString.concat(s);
                if((bufferReadToString.indexOf(cutoffASCII) + 1) > 0) {
                    String outputString = bufferReadToString.substring(0, bufferReadToString.indexOf(cutoffASCII) + 1);
                    bufferReadToString = bufferReadToString.substring(bufferReadToString.indexOf(cutoffASCII) + 1);
		    //System.out.print(outputString);
		    String vystup[] = outputString.split(":");
		    if (vystup.length == 6) {
		    	//System.out.println(vystup[4]);
		    	//System.out.print("U:"+vystup[1]+"I:"+vystup[2]+"P:"+vystup[3]+"Tarif:"+vystup[4]+"T:"+vystup[5]);
			AktualniHodnoty.frekvence = Integer.parseInt(vystup[0]);
			AktualniHodnoty.napeti = Float.parseFloat(vystup[1]);
			if(Float.parseFloat(vystup[3])>15)
			{
			AktualniHodnoty.proud = Float.parseFloat(vystup[2]);
			AktualniHodnoty.prikon = Float.parseFloat(vystup[3]);
			if(Integer.parseInt(vystup[4])==0) //hodnota 0 pro nizky a 1 pro vysoky
			{
			  AktualniHodnoty.spotrebaNT = AktualniHodnoty.spotrebaNT + (Float.parseFloat(vystup[3])*Float.parseFloat(vystup[5])/1000)/3600;
			} else
				{
				AktualniHodnoty.spotrebaVT = AktualniHodnoty.spotrebaVT + (Float.parseFloat(vystup[3])*Float.parseFloat(vystup[5])/1000)/3600;
			       }	
			}
			else{
				AktualniHodnoty.proud = 0;
				AktualniHodnoty.prikon = 0;
			}
			try {
			    /*
			    FileWriter myWriter = new FileWriter("filename");
      			    myWriter.write("Files in Java might be tricky, but it is fun enough!");
      			    myWriter.close();
			    */
			    FileWriter NT = new FileWriter("SpotrebaNT");
      			    NT.write(String.valueOf(AktualniHodnoty.spotrebaNT));
      			    NT.close();

			    FileWriter VT = new FileWriter("SpotrebaVT");
      			    VT.write(String.valueOf(AktualniHodnoty.spotrebaVT));
      			    VT.close();

		
			    }catch (IOException except) {
			    	System.out.println("Error with opening file.");
			}
		    } else {
			System.out.println("Flushing serial link.");

//                    System.out.print(outputString);

                    }
                }
      }
}
