package com.qmth.jkserver;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;

import com.qmth.jkserver.constant.SystemConstant;
import org.apache.commons.io.IOUtils;

import com.qmth.jkserver.common.MD5;
import com.qmth.jkserver.core.exception.JkServerException;

/**
 * 通用题库 优特答案数据包解码操作
 * @author tianjun
 *
 */
public class FileDecodeTest {
	
	private static final File ROOT = new File("E:\\RESOURCE_RUNNING\\output");
	
	public static void decode(File file) throws IOException{
		byte[] startBytes = new byte[23];	//zip头部块
		byte[] endBytes = new byte[23];		//zip尾部块
		byte[] loop = new byte[41];			
		RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
		File ansFile = new File(ROOT, file.getName() + SystemConstant.ZIP_PREFIX);
		if(!ansFile.exists()){
			ansFile.createNewFile();
		}
		BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(ansFile));
		if(file.length()<(136+54)){
			throw new JkServerException("文件结构错误");
		}
		randomAccessFile.seek(file.length()-54);
		int len = 0;
		len = randomAccessFile.read(startBytes);
		os.write(startBytes);
		if(len!=23){
			throw new JkServerException("文件结构错误,头部23字节读取失败");
		}
		len = randomAccessFile.read(endBytes);
		if(len!=23){
			throw new JkServerException("文件结构错误,尾部23字节读取失败");
		}
		long total = file.length()-54-136;
		//每次读取41字节 计算需要读取多少次，以及最后一次需要读取多少字节
		int count = new Double(Math.floor(total / 41)).intValue();	//读取次数
		int left = new Double(total % 41).intValue();	//最后一次读取多少字节
		//开始读取中间的部分
		randomAccessFile.seek(file.length()-54-left);
		byte[] leftBytes = new byte[left];
		len = randomAccessFile.read(leftBytes);
		if(len != left){
			throw new JkServerException("加密文件结构错误,尾部字节读取错误");
		}
		else{
			os.write(leftBytes);
		}
		for (int i=0;i<count;i++) {
			randomAccessFile.seek(file.length()-54-left-(i+1)*41);
			len = randomAccessFile.read(loop);
			if(len!=41){
				throw new JkServerException("加密文件结构错误");
			}
			else{
				os.write(loop);
			}
		}
		os.write(endBytes);
		IOUtils.closeQuietly(os);
		randomAccessFile.close();
		if(ansFile.length() != file.length()-144){
			throw new JkServerException("文件解码失败");
		}
	}
	
	public static void main(String[] args) throws IOException {
			decode(new File("E:\\11111111\\jkserver\\420101_42010101_20180516124729.qm"));
	}

}
