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

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;

import com.alibaba.fastjson.JSONArray;
import com.wisedu.coeus.core.ConstantStatic;

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.coeus.util.json.JSONObject;
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 AliyunVideoHandler implements Handler {

	private static final Logger log = LoggerFactory.getLogger(AliyunVideoHandler.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;
                //上传视频成功后，进行发送get请求进行云监控数据的上报
                if (ConstantStatic.MONITOR_FLAG){ //监控上报设置为true
                    sendMonitorHttp();
                }

			}

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

	}

    private void sendMonitorHttp() {
        Date date = new Date();
        String url = ConstantStatic.MONITOR_URL;
        String userId =ConstantStatic.MONITOR_USERID;
        String namespace = ConstantStatic.MONITOR_NAMESPACE;
        JSONArray array = new JSONArray();
        JSONObject json = new JSONObject();
        json.put("metricName",ConstantStatic.MONITOR_METRICNAME);
        json.put("timestamp",date.getTime());
        json.put("value",1);
        json.put("unit",ConstantStatic.MONITOR_UNIT);
        //dimension
        JSONObject dimensionObject = new JSONObject();
        dimensionObject.put(ConstantStatic.MONITOR_DIMENSION_KEY,ConstantStatic.MONITOR_DIMENSION_VALUE);
        json.put("dimensions",dimensionObject);
        array.add(json);
        String metrics = JSONArray.toJSONString(array);
        url = url.concat("?userId=").concat(URLEncoder.encode(userId)).concat("&namespace=").concat(URLEncoder.encode(namespace)).concat("&metrics=").concat(URLEncoder.encode(metrics));
        HttpURLConnection connection = null;
        try {
            URL getUrl = new URL(url);
            connection = (HttpURLConnection) getUrl.openConnection();
            connection.connect();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        connection.disconnect();
    }

}
