package com.lerx.v6.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.util.DigestUtils;

import com.lerx.entities.UploadedFile;
import com.lerx.portal.obj.UploadArgs;
import com.lerx.sys.obj.FileInf;
import com.lerx.sys.util.FileUtil;
import com.lerx.sys.util.HttpUtil;
import com.lerx.sys.util.StringUtil;
import com.lerx.sys.util.SysUtil;

public class UploadUtil {
	
	public static UploadedFile coverFromFi(FileInf fi){
		UploadedFile uf = new UploadedFile();
		uf.setUrl(fi.getUrl());
		uf.setFullPath(fi.getFullPath());
		uf.setExt(fi.getExt());
		uf.setNameNoExt(fi.getNameNoExt());
		uf.setRealPath(fi.getRealPath());
		uf.setSize(fi.getSize());
		uf.setUploadDatetime(fi.getAddtime());
		uf.setMd5(fi.getMd5());
		return uf;
	}
	
	public static UploadedFile upload(UploadArgs ua) throws IOException {
		FileInf fi;
		if (ua.getCw()==0 && ua.getCh()==0){
			fi = FileUtil.upload(ua.getFile(), ua.getTargetFile());
		}else{
			fi = FileUtil.upload(ua.getFile(), ua.getTargetFile(), ua.getCw(), ua.getCh());
		}
		String filenameNoExt = fi.getNameNoExt();
		fi.setNameNoExt(filenameNoExt);
		UploadedFile fu = UploadUtil.coverFromFi(fi);
		fu.setUser(ua.getUserDaoImpl().findByID(ua.getUid()));
		fu.setRemark(ua.getTitle());
		UploadedFile existu = ua.getUploadedFileDaoImpl().findByMD5(fu.getMd5(), fu.getId());
		UploadedFile ue;
		if (existu != null) {
			FileUtil.delete(fu.getFullPath());
			ue = existu;
		} else {
			ue = fu;
			ua.getUploadedFileDaoImpl().add(ue);
		}

		return ue;
	}
	
	
	public static UploadedFile downUrlFile(UploadArgs ua,String url,HttpServletRequest request,HttpServletResponse response) {
		long uid=ua.getUid();
		ResourceBundleMessageSource messageSource=ua.getMessageSource();
		url=StringUtil.strReplace(url, "www.jysedu.com", "www.jycfd.cn");
		url=HttpUtil.repairUrl(url);
		String filename=FileUtil.getFileFromPath(url);
		String currUrl = SysUtil.uploadTarget(messageSource, filename, null, uid);
		String realFile=FileUtil.appPath()+File.separator+currUrl;
		realFile=FileUtil.repairFilePath(realFile);
		String realPath=FileUtil.dir(realFile);
		realPath=FileUtil.repairFilePath(realPath);
		File filePath = new File(realPath);
		if (!filePath.exists()) {
			filePath.mkdirs();
			FileUtil.erable(filePath);
		}

		URL urlfile = null;
		HttpURLConnection httpUrl = null;
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		File f = new File(realFile);
		try {
//			System.out.println("url:"+url);
			urlfile = new URL(url);
			httpUrl = (HttpURLConnection) urlfile.openConnection();
			httpUrl.connect();
			bis = new BufferedInputStream(httpUrl.getInputStream());
			bos = new BufferedOutputStream(new FileOutputStream(f));
			int len = 2048;
			byte[] b = new byte[len];
			while ((len = bis.read(b)) != -1) {
				bos.write(b, 0, len);
			}

			bos.flush();
			bos.close();
			bis.close();
			httpUrl.disconnect();
			FileInputStream fis = new FileInputStream(realFile);
			
			String md5 = DigestUtils.md5DigestAsHex(IOUtils.toByteArray(fis));
			FileInf fi = new FileInf();
			fi.setAddtime(System.currentTimeMillis());
			fi.setFullPath(realFile);
			fi.setMd5(md5);
			
			if (currUrl.indexOf("://") < 0) {
				currUrl=request.getContextPath()+"/"+currUrl;
				currUrl=HttpUtil.repairUrl(currUrl);
			}
			
			fi.setUrl(currUrl);
			fi.setNameNoExt(FileUtil.getFileName(realFile));
			fi.setRealPath(realPath);
			fi.setSize(FileUtils.sizeOf(f));
			UploadedFile fu = UploadUtil.coverFromFi(fi);
			fu.setUser(ua.getUserDaoImpl().findByID(ua.getUid()));
			fu.setRemark(ua.getTitle());
			UploadedFile existu = ua.getUploadedFileDaoImpl().findByMD5(fu.getMd5(), fu.getId());
			UploadedFile ue;
			if (existu != null) {
				FileUtil.delete(fu.getFullPath());
				ue = existu;
			} else {
				ue = fu;
				ua.getUploadedFileDaoImpl().add(ue);
			}
			
			FileUtil.erable(f);

			return ue;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
	}

}
