package com.mq.mylibrary.rfid.io.translate;

import com.fntech.RInt;
import com.mq.mylibrary.rfid.io.cmd.TXFRAME;
import com.mq.mylibrary.rfid.io.translate.frame.ApduFrame;

public class TxApdu {

	public static void tx_apdu_to_frame(TXFRAME frame, ApduFrame aFrame){
		frame.mac_no = TXFRAME.MACNO;
		frame.tx_len = 2 + 4;
		TXFRAME.tx_make_iso14443_cmd(frame.tx_data);
		frame.tx_data[2] = aFrame.CLA;
		frame.tx_data[3] = aFrame.INS;
		frame.tx_data[4] = aFrame.P1;
		frame.tx_data[5] = aFrame.P2;

		//Lc
		if (aFrame.Lc != (byte)0xFF){
			frame.tx_data[frame.tx_len] = aFrame.Lc;
			frame.tx_len += 1;
			if (aFrame.Lc != 0x00){
				//待添加
				//memcpy(frame.tx_data[frame.tx_len], fmcos.DATA, fmcos.Lc);
				System.arraycopy(aFrame.DATA, 0, frame.tx_data, frame.tx_len, aFrame.Lc);
				frame.tx_len += aFrame.Lc;
			}
		}
		//Le
		if (aFrame.Le != (byte)0xFF){
			frame.tx_data[frame.tx_len] = aFrame.Le;
			frame.tx_len += 1;
		}

		frame.crc_enable = TXFRAME.CRC3;
		frame.bit_framing = 0;
		frame.timeout_count = TXFRAME.TX_COUNT;
	}
	
	public static short apdu_parse_status2(byte[] recv, int len){
		short status = 0;
		status = (short) ((recv[len - 1]&0xFF) +((recv[len - 2]&0xFF)<<8));
		if ((status==ApduFrame.APDU_RESP_OK)){
			return 0;
		}

		if (status == 0)
			status = (short) 0xFFFF;

		return status;
	}
	
	void tx_apdu_buf_to_frame(TXFRAME frame, byte[] req, int len){
		frame.mac_no = TXFRAME.MACNO;
		frame.tx_len = 2 + len;
		TXFRAME.tx_make_iso14443_cmd(frame.tx_data);
		//memcpy(Tools.cutByte(frame.tx_data, 2), req, len);
		System.arraycopy(req, 0, frame.tx_data, 2, len);
		
		frame.crc_enable = TXFRAME.CRC3;
		frame.bit_framing = 0;
		frame.timeout_count = TXFRAME.TX_COUNT;
	}
	public static short tx_apdu_parse_frame_status(TXFRAME frame){
		return apdu_parse_status2(frame.rx_data, frame.rx_len);
	}

	public static int tx_apdu_parse_frame(TXFRAME frame, byte[] buf, byte len){
		int result = -1;
		result = tx_apdu_parse_frame_status(frame);
		if (result == 0){
			len = (byte) (frame.rx_len - 2);
			System.arraycopy(frame.rx_data, 0, buf, 0, len);
			return 0;
		}
		return result;
	}
	
	public static int tx_apdu_parse_frame2(TXFRAME frame, byte[] buf, RInt len){
		int result = -1;
		result = tx_apdu_parse_frame_status(frame);
		if (result == 0){
			len.len = (byte) ((byte)frame.rx_len - 2);
			System.arraycopy(frame.rx_data, 0, buf, 0, len.len);
			return 0;
		}
		return result;
	}
	
}
