package com.baidu.ueditor.upload;

import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.State;


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

import com.sifang.modules.alioss.AliyunOSSClientUtil;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.utils.SpringContextHolder;
import com.sifang.modules.sys.util.IOUtil;
import org.apache.commons.io.FileUtils;

public class StorageManager {
	public static final int BUFFER_SIZE = 8192;

	public StorageManager() {
	}

	public static State saveBinaryFile(byte[] data, String path) {
		File file = new File(path);

		State state = valid(file);

		if (!state.isSuccess()) {
			return state;
		}

		try {
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(file));
			bos.write(data);
			bos.flush();
			bos.close();
			
		} catch (IOException ioe) {
			return new BaseState(false, AppInfo.IO_ERROR);
		}

		state = new BaseState(true, file.getAbsolutePath());
		state.putInfo( "size", data.length );
		state.putInfo( "title", file.getName() );
		
		state = saveSfFiles(IOUtil.byte2InputStream(data), path);
		System.out.println(state.toJSONString());
		
		return state;
	}

	public static State saveFileByInputStream(InputStream is, String path,
			long maxSize) {
		State state = null;

		File tmpFile = getTmpFile();

		//byte[] dataBuf = new byte[ 2048 ];
		//BufferedInputStream bis = new BufferedInputStream(is, StorageManager.BUFFER_SIZE);

		try {
			/*BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(tmpFile), StorageManager.BUFFER_SIZE);

			int count = 0;
			while ((count = bis.read(dataBuf)) != -1) {
				bos.write(dataBuf, 0, count);
			}
			bos.flush();
			bos.close();

			if (tmpFile.length() > maxSize) {
				tmpFile.delete();
				return new BaseState(false, AppInfo.MAX_SIZE);
			}*/

			//state = saveTmpFile(tmpFile, path);
			state = saveSfFiles(is, path);
			System.out.println(state.toJSONString());

			if (!state.isSuccess()) {
				tmpFile.delete();
			}

			return state;
			
		} catch (Exception e) {
		}
		return new BaseState(false, AppInfo.IO_ERROR);
	}

	public static State saveFileByInputStream(InputStream is, String path) {
		State state = null;

		File tmpFile = getTmpFile();

		//byte[] dataBuf = new byte[ 2048 ];
		//BufferedInputStream bis = new BufferedInputStream(is, StorageManager.BUFFER_SIZE);

		try {
			/*BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(tmpFile), StorageManager.BUFFER_SIZE);

			int count = 0;
			while ((count = bis.read(dataBuf)) != -1) {
				bos.write(dataBuf, 0, count);
			}
			bos.flush();
			bos.close();*/

			//state = saveTmpFile(tmpFile, path);
			state = saveSfFiles(is, path);
			System.out.println(state.toJSONString());

			if (!state.isSuccess()) {
				tmpFile.delete();
			}

			return state;
		} catch (Exception e) {
		}
		return new BaseState(false, AppInfo.IO_ERROR);
	}

	private static File getTmpFile() {
		File tmpDir = FileUtils.getTempDirectory();
		String tmpFileName = (Math.random() * 10000 + "").replace(".", "");
		return new File(tmpDir, tmpFileName);
	}

	private static State saveTmpFile(File tmpFile, String path) {
		State state = null;
		File targetFile = new File(path);

		if (targetFile.canWrite()) {
			return new BaseState(false, AppInfo.PERMISSION_DENIED);
		}
		try {
			FileUtils.moveFile(tmpFile, targetFile);
		} catch (IOException e) {
			return new BaseState(false, AppInfo.IO_ERROR);
		}

		state = new BaseState(true);
		state.putInfo( "size", targetFile.length() );
		state.putInfo( "title", targetFile.getName() );
		
		return state;
	}

	private static State valid(File file) {
		File parentPath = file.getParentFile();

		if ((!parentPath.exists()) && (!parentPath.mkdirs())) {
			return new BaseState(false, AppInfo.FAILED_CREATE_FILE);
		}

		if (!parentPath.canWrite()) {
			return new BaseState(false, AppInfo.PERMISSION_DENIED);
		}

		return new BaseState(true);
	}
	
	public static State saveSfFiles(InputStream is, String path){
		State state = null;

		String extName = StringUtil.getFileExtName(path);

		try {
			//String webPath = ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/");
			/*File tempDir = new File(webPath + File.separator + "temp");
			if (!tempDir.exists()) {
				tempDir.mkdirs();
			}
			String tempFilePath = tempDir.getAbsolutePath() + File.separator + IdGen.uuid() + "." + extName;
			ImageUtil.compressImage(is, tempFilePath, 1024);
			File tempFile = new File(tempFilePath);*/
			byte[] isByte = IOUtil.in2byte(is);
			String fileInfo = AliyunOSSClientUtil.uploadImage(isByte, extName,"");
			/*if(StringUtils.isNotBlank(fileInfo.getPath())){
				//上传成功，需要删除临时文件
				FileUtils.deleteQuietly(tempFile);
				System.out.println(fileInfo.toString());
			}*/
			state = new BaseState(true);
			state.putInfo( "size", isByte.length);
			state.putInfo( "title", "");
			state.putInfo("url", StringUtil.trasferBackslash(fileInfo));
		}catch(Exception e){
			e.printStackTrace();
			state = new BaseState(false);
		}
		return state;
	}
}