package org.josast.AX25;

import java.util.logging.Level;
import java.util.logging.Logger;

public class KissFrame {

	public static final int AX25 = 0;
	public static final int TXDELAY = 1;
	public static final int P = 2;
	public static final int SlotTime = 3;
	public static final int TXtail = 4;
	public static final int Fullduplex = 5;
	public static final int SetHardware = 6;
	public static final int Exit = 255;
	public static final int unknow = -1;
	public int cptcontents=0;

	private Logger log = Logger.getLogger(getClass().getName());
	
	private byte type;
	
	private byte  []  contents= new byte[1050];


	public void setType(byte ax252) {
		 type = ax252;
	}
	
	public byte  DecodeKissType(byte val) {
		
		 switch (val) {
		 case 0x00: type = AX25;
		 log.log(Level.INFO, "AX25 type");
		 break;
		 case 0x01: type =  TXDELAY;
		 break;
		 case 0x02: type =  P;
		 break;
		 case 0x03: type =  SlotTime;
		 break;
		 case 0x04: type =  TXtail;
		 break;
		 case 0x05: type =  Fullduplex;
		 break;
		 case 0x07: type  = SetHardware;
		 break;
		 case (byte) 0xFF: type  = (byte) Exit;
		 break;	 
		 default :  type  = unknow;
		 log.log(Level.INFO, "unknow type");
		 }

	return type;
	}
	
	
	
	public KissData extactMessage(byte[] frame, int nb )
	{
		KissData kissData; 
		
		 type=unknow;
		 
		 boolean startFrame = false;
		 boolean endFrame = false;
		 int cpt=0;
		 cptcontents=0;
		 
		 // detect start frame
		 while (!startFrame )
		 {
			 if (((byte)frame[cpt++] & 0xFF)== 0xC0)
				{
				 startFrame = true;
				}
			 if (cpt==nb)
			 {
				 startFrame = true;
				 endFrame = true;
				}
		 }
		 // identify frame
		 type = DecodeKissType ((byte)( frame[cpt++] & 0xFF));
		 
		 // Extract data
		 while (!endFrame  )
		 {
			
			if (((int)frame[cpt] & 0xFF)== 0xDB)
				 {
					 cpt++;
				 }
			if (((int)frame[cpt] & 0xFF)== 0xDD)
			 {
				 cpt++;
			 }	
			
			if (((int)frame[cpt] & 0xFF)== 0xC0)
			{
			 endFrame = true;
			}
			contents[cptcontents++] =(byte)(frame[cpt++] & 0xFF);					
			 
			 if (cpt>=nb)
			 {
				 endFrame = true;
			}
				
		 }	
		 kissData = new KissData(contents,cptcontents);
		return kissData;
		
	}
	
	
}
