package com.qy.utils;

import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.PrintWriter;

import com.qy.ui.AppMain;
import com.sun.org.apache.xml.internal.security.utils.Base64;


public class JarToBase {

	public static void start(String jarPath,boolean isBase)  {
		// TODO Auto-generated method stub
			try {
				new JarToBase(jarPath,isBase);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	public JarToBase(String jarPath,boolean isBase) throws Exception {
		// TODO Auto-generated constructor stub
		if(isBase) {
		encode(jarPath);
		}else {
			decode(jarPath);
		}
	}
	public void decode(String basePath) throws Exception{
		File file=new File(basePath);
		File out=new File(new File("").getAbsolutePath()+File.separator+file.getName().split("\\.")[0]+".jar");
		BufferedReader reader=new BufferedReader(new FileReader(file));
		String tmp,str="";
		while ((tmp=reader.readLine())!=null) {
			str+=tmp;
		}
		byte[] b=Base64.decode(str);
		DataOutputStream outputStream=new DataOutputStream(new FileOutputStream(out));
		outputStream.write(b);
		outputStream.flush();
		outputStream.close();
		reader.close();
		if(AppMain.isOpenWindows)
		Desktop.getDesktop().open(new File(new File("").getAbsolutePath()));
	}
	public void encode(String jarPath)throws Exception{
		File file=new File(jarPath);
		DataInputStream inputStream=new DataInputStream(new FileInputStream(file));
		byte[] b=new byte[inputStream.available()];
		while ((inputStream.read(b))!=-1) {
		}
		inputStream.close();
		
		String str=new String(Base64.encode(b));
	//	System.out.println(str);
		save(str,file.getName().split("\\.")[0]);
	}
	public void save(String str,String name )throws Exception {
		File file=new File(new File("").getAbsolutePath()+File.separator+name+".lt");
		System.out.println("����λ��:"+file.getAbsolutePath());
		file.createNewFile();
		PrintWriter writer=new PrintWriter(file);
		writer.write(str);
		writer.flush();
		writer.close();
		if(AppMain.isOpenWindows)
		Desktop.getDesktop().open(new File(file.getAbsolutePath().substring(0, file.getAbsolutePath().length()-file.getName().length())));
	}

}
