package com.wisedu.mooc.app.thirdparty.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import com.wisedu.coeus.debug.Logger;
import com.wisedu.coeus.debug.LoggerFactory;
import com.wisedu.coeus.util.FileUtils;
import com.wisedu.coeus.util.Strings;
import com.wisedu.mooc.app.thirdparty.service.Handler;
import com.wisedu.mooc.app.upload.RsConstant;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

/**
 * 阿里云OSS图片处理类
 * @author 01115035
 *
 */
public class AliyunImageHandler implements Handler {

	private static final Logger log = LoggerFactory.getLogger(AliyunImageHandler.class);

	public static OSSClient client;


	/**
	 * 初始化阿里云OSSClient
	 */
	@Override
	public void initHandler() {
		if (client == null) {
			/**根据配置文件值初始化OSSClient **/
			client = new OSSClient(RsConstant.ALIYUN_OSS_END_POINT, RsConstant.ALIYUN_ACCESS_KEY_ID, RsConstant.ALIYUN_SECRET_ACCESS_KEY);
		}
		
	}
	
	
	/**
	 * 校验阿里云OSSClient链接是否成功
	 */
	@Override
    public boolean check(){
		boolean flag = false;
		try{
			if(client == null){
				initHandler();
			}
        	//client.listBuckets();
            flag = true;
        }catch (RuntimeException e){
            log.error(e.getMessage(),e);
        }
        return flag;
    }

	/**
	 * 上传文件
	 */
	@Override
	public boolean uploadFile(File file, String targetFilePath) {
		InputStream content = null;
		boolean flag = false;
		try {
			log.debug("begin build ObjectMetadata:{} to {}", file.getAbsoluteFile(),targetFilePath);
			content = new FileInputStream(file);
			// 创建上传Object的Metadata
			ObjectMetadata objectMetadata = new ObjectMetadata();
			//objectMetadata.setContentLength(content.available());
			//objectMetadata.setContentType(FileUtils.getContentTypeByFileExt(FileUtils.getExtName(file.getName())));//设置文件ContentType类型
			log.debug("build ObjectMetadata end:{} to {}", file.getAbsoluteFile(),targetFilePath);
			
			log.debug("begin upload file:{} to {}", file.getAbsoluteFile(),targetFilePath);
			
			//上传文件
			PutObjectResult result = client.putObject(RsConstant.ALIYUN_SOURCE_BUCKET_NAME, targetFilePath, content,
					objectMetadata);
			
			//文件返回值
			if(result != null && Strings.isNotEmpty(result.getETag())){
				log.debug("upload over file:{}!", file.getAbsoluteFile());
				flag = true;
			}

		} catch (IOException e) {
			log.error(e.getMessage(), e);
		} catch (RuntimeException e){
            log.error(e.getMessage(),e);
        }
		return flag;

	}

}
