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 java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.qmth.jkserver.constant.SystemConstant;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import com.qmth.jkserver.core.exception.JkServerException;

/**
 * 通用题库 优特答案数据包解码操作
 * @author tianjun
 *
 */
public class FileDecodeTestBak {
	
	private static final File ROOT = new File("E:\\RESOURCE_RUNNING\\output");
	
	public static void decode(File file) throws IOException{
		//去除头部尾部，生成内容块
		RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
		File target = new File(ROOT, SystemConstant.getNanoId() + ".qmtmp");
		if(!target.exists()){
			target.createNewFile();
		}
		byte bytes[] = new byte[1024];
		int len = 0;
		randomAccessFile.seek(136);	//跳过头部 136个字节读取，尾部8个字节不读取
		long max = file.length()-8; //指针的最大位移
		BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(target));
		long total = 0;
		while((len=randomAccessFile.read(bytes)) > 0){
			if(randomAccessFile.getFilePointer() <= max){
				outputStream.write(bytes, 0, len);
				total +=len;
			}else{
				long left = file.length()-144-total;
				if(left > 0){
					outputStream.write(bytes, 0, Integer.valueOf(left + ""));
				}
			}
		}
		randomAccessFile.close();
		outputStream.flush();
		IOUtils.closeQuietly(outputStream);
		if(target.length() != (file.length()-144)){
			throw new JkServerException(JkServerException.DECODE_ANSWER_FILE_ERROR.getCode(),
					"去除文件首尾时字节读取错误");
		}
		//内容段字节块顺序重排
		RandomAccessFile targetAccessFile = new RandomAccessFile(target, "rw");
		byte[] startBytes = new byte[23];
		byte[] endBytes = new byte[23];
		byte[] reads = new byte[41];
		List<byte[]> container = new ArrayList<byte[]>();
		len = 0;
		total = 0;
		max = target.length()-46;
		targetAccessFile.seek(0);
		while((len=targetAccessFile.read(reads)) > 0){
				if(targetAccessFile.getFilePointer() <= max){
					if(len == 41){
						container.add(cloneByteArray(reads));
						total += len;
					}
					else{
						throw new JkServerException("文件结构错误");
					}
				}
				else{
					long left = target.length()-46-total;
					if(left > 0){
						byte[] last = new byte[Integer.valueOf(left+"")];
						for (int i=0;i<left;i++) {
							last[i] = reads[i];
						}
						container.add(last);
						total += left;
					}
				}
		}
		if(total!=target.length() - 46){
			throw new JkServerException("文件结构错误");
		}
		targetAccessFile.seek(target.length()-46);
		int a = targetAccessFile.read(startBytes);
		if(a!=23){
			throw new JkServerException("文件结构错误");
		}
		int b = targetAccessFile.read(endBytes);
		if(b!=23){
			throw new JkServerException("文件结构错误");
		}
		targetAccessFile.close();
		//输出到文件里面
		File ansFile = new File(ROOT,"answer_"+new SimpleDateFormat("yyyy-MM-dd-HHmmss").format(new Date()) + SystemConstant.ZIP_PREFIX);
		if(!ansFile.exists()){
			ansFile.createNewFile();
		}
		BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(ansFile));
		os.write(startBytes);//写入头部23字节
		//倒序写入
		for (int i=container.size()-1;i>=0;i--) {
			os.write(container.get(i));
		}
		os.write(endBytes);
		os.flush();
		IOUtils.closeQuietly(os);
		if(target.length() != ansFile.length()){
			throw new JkServerException("文件解码失败");
		}
		FileUtils.forceDelete(target);
	}
	//复制数组a中的字节
	protected static byte[] cloneByteArray(byte[] a){
		byte[] result = new byte[a.length];
		for (int i=0;i<result.length;i++) {
			result[i] = a[i];
		}
		return result;
	}
	
	public static void main(String[] args) {
		try {
			decode(new File("E:\\RESOURCE_RUNNING\\test\\420101_42010101_20171026145351.qm"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
