package com.jisco.dynamicweight.dynamicbasecamera.service.impl;

import com.jisco.dynamicweight.dynamicbasecamera.factories.Converter;
import com.jisco.dynamicweight.dynamicbasecamera.factories.ConverterFactories;
import com.jisco.dynamicweight.dynamicbasecamera.service.IFLVService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * FLV流转换
 * 
 * @author hzj
 */

@Service(value = "flvService")
public class FLVService implements IFLVService {
	private static Logger logger	= LoggerFactory.getLogger( FLVService.class );
	private Map<String, Converter> converters = new HashMap<String, Converter>();

	@Override
	public void open(String url,String videoId, HttpServletResponse response, HttpServletRequest request) {
		String key = md5(url);

		AsyncContext async = request.startAsync();
		async.setTimeout(0);
		if (converters.containsKey(key) && url.indexOf("/tracks")==-1) {
			Converter c = converters.get(key);
			try {
				c.addOutputStreamEntity(key, async);
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				throw new IllegalArgumentException(e.getMessage());
			}
		} else {
		   Converter converter = converters.get(key);
			if(converter!=null){
				converter.exit();
			}
			List<AsyncContext> outs = new ArrayList<AsyncContext>();
			outs.add(async);
			ConverterFactories c = new ConverterFactories(url, key, converters, outs,videoId);
			c.start();
			converters.put(key, c);
		}

		response.setContentType("video/x-flv");
		response.setHeader("Connection", "keep-alive");

		try {
			//response.getWriter().write("{\"code\":200}");
			response.setStatus(HttpServletResponse.SC_OK);
			response.flushBuffer();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
	}

	public String md5(String plainText) {
		StringBuilder buf = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());
			byte b[] = md.digest();
			int i;
			buf = new StringBuilder("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
				{
					i += 256;
				}
				if (i < 16)
				{
					buf.append("0");
				}
				buf.append(Integer.toHexString(i));
			}
		} catch (NoSuchAlgorithmException e) {
			logger.error(e.getMessage(), e);
		}
		return buf.toString();
	}

}
