package com.platform.plugs.live.utils;

import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.NumberUtils;
import org.apache.commons.lang.StringUtils;

import com.platform.plugs.live.config.LiveStreamConfig;

/**	
 * @Author TONG
 * @Date 2019/2/19 15:22
 **/
public class StreamAddressUtils {

    //30分
    private static final int DEFAULT_AUTH_TIME = 1800;

    private static final String MD5_KEY_FORMAT = "/%s/%s-%d-%s-0-%s";

    private static final String NO_AUTH_PUSH_URL = "rtmp://%s/%s/%s";

    private static final String RTMP_URL_FORMAT = "rtmp://%s/%s/%s?auth_key=%d-%s-0-%s";
    private static final String HTTP_URL_FORMAT = "https://%s/%s/%s?auth_key=%d-%s-0-%s";
    
    
    private static final String QUERY_TIMELINE = "http://%s/openapi/timeline/query?aliyunols=on&app=%s&stream=%s&format=ts&lhs_start_unix_s_0=%d&lhs_end_unix_s_0=%d&auth_key=%d-%s-0-%s";
    private static final String QUERY_TIMELINE_MD5_KEY_FORMAT = "/openapi/timeline/query-%d-%s-0-%s";


    /**
     * 生成推流地址
     * @param startDate
     * @param endDate
     * @param appName
     * @param streamName
     * @return
     */
    public static String generatePushUrl(Date startDate, Date endDate, String appName, String streamName, LiveStreamConfig streamConfig) {
        return generateUrl(startDate, endDate, appName, streamName, streamConfig.getPushDomain(), streamConfig.getPushKey(), streamConfig.getPushAuthTime());
    }

    /**
     * 生成播流地址
     *
     * @param startDate
     * @param endDate
     * @param appName
     * @param streamName
     * @return
     */
    public static String[] generateLiveUrl(Date startDate, Date endDate, String appName, String streamName, LiveStreamConfig streamConfig) {
        String domain = streamConfig.getLiveDomain();
        String key = streamConfig.getLiveKey();
        Integer authTime = streamConfig.getLiveAuthTime();
        String[] liveUrls = new String[] {
                generateUrl(startDate, endDate, appName, streamName, domain, key, authTime, RTMP_URL_FORMAT),
                generateUrl(startDate, endDate, appName, streamName + ".flv", domain, key, authTime, HTTP_URL_FORMAT),
                generateUrl(startDate, endDate, appName, streamName + ".m3u8", domain, key, authTime, HTTP_URL_FORMAT)
        };
        return liveUrls;
    }
    
    /**
     * 生成直播时移地址
     *
     * @param startDate
     * @param endDate
     * @param appName
     * @param streamName
     * @return
     */
    public static String generateTimeShiftUrl(Date startDate,String appName, String streamName, LiveStreamConfig streamConfig) {
        int time = (int) (startDate.getTime() / 1000) + streamConfig.getTimeShiftAuthTime();
        String uuid = "0";
        String md5key = String.format(MD5_KEY_FORMAT, appName, streamName+ ".m3u8", time, uuid, streamConfig.getLiveKey());
        return String.format(HTTP_URL_FORMAT, streamConfig.getLiveDomain(), appName, streamName + ".m3u8", time, uuid, DigestUtils.md5Hex(md5key.getBytes()));
    }
    
    /**
     * 生成直播时移时间轴查询地址
     * @param startDate
     * @param endDate
     * @param appName
     * @param streamName
     * @return
     */
    public static String generateQueryTimeLineUrl(int startDate, int endDate, String appName, String streamName, LiveStreamConfig streamConfig) {
        String uuid = "0";
        int time = (int) (new Date().getTime() / 1000) + 1800;
        String md5key = String.format(QUERY_TIMELINE_MD5_KEY_FORMAT, time, uuid, streamConfig.getLiveKey());
        return String.format(QUERY_TIMELINE, "live.zhongkedongxin.com", appName, streamName, startDate,endDate, time,uuid, DigestUtils.md5Hex(md5key));
    }

    private static String generateUrl(Date startDate, Date endDate, String appName, String streamName, String domainName, String authKey, Integer configAuthTime) {

        return generateUrl(startDate, endDate, appName, streamName, domainName, authKey, configAuthTime, RTMP_URL_FORMAT);
    }

    private static String generateUrl(Date startDate, Date endDate, String appName, String streamName, String domainName, String authKey, Integer configAuthTime, String urlFormat) {

        if(StringUtils.isBlank(appName) || StringUtils.isBlank(streamName) || StringUtils.isBlank(domainName))
            return null;

        if(StringUtils.isBlank(authKey))
            return String.format(NO_AUTH_PUSH_URL, domainName, appName, streamName);

        int authTime = DEFAULT_AUTH_TIME;
        int time = 0;
        if(startDate == null)
            startDate = new Date();
        if(endDate != null && endDate.compareTo(startDate) > 0 && endDate.compareTo(new Date()) > 0) {
            time = (int)(endDate.getTime() / 1000);
        }
        if(configAuthTime != null)
            authTime = configAuthTime;

        if(time == 0)
            time = (int) (startDate.getTime() / 1000) + authTime;
//        int time = 1550563005;
//        String uuid = UUID.randomUUID().toString().replace("-", "");
        String uuid = "0";
        String md5key = String.format(MD5_KEY_FORMAT, appName, streamName, time, uuid, authKey);
        return String.format(urlFormat, domainName, appName, streamName, time, uuid, DigestUtils.md5Hex(md5key.getBytes()));
    }

    /**
     * 路径是否过期(true 为过期 ，false 没有过期)
     *
     * @param url
     * @return
     */
    public static boolean isExpire(String url) {

        if (StringUtils.isEmpty(url)) {
            return true;
        }
        if(!url.contains("auth_key")) return false;

        String[] authKeyParams = url.trim().split("auth_key");
        if (authKeyParams.length == 2) {
            String authKeyParam = authKeyParams[1].substring(1);
            String timeStamp = authKeyParam.substring(0, authKeyParam.indexOf("-"));
            if (NumberUtils.isDigits(timeStamp)) {
                if ((Integer.parseInt(timeStamp) - 600) >= (int) (System.currentTimeMillis() / 1000)) {
                    return false;
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
//        System.out.println(StreamAddressUtils.isExpire("rtmp://live.zhongkedongxin.com/test/test?auth_key=1550564223-0-0-c9ca3ec6f5d14456e64cf6af5f9f5e48"));


//        LiveStreamConfig streamConfig = new LiveStreamConfig("", "", "live.zhongkedongxin.com", "iim00IV2CF");
//        
//        int startDate = 1583376633;
//        int endDate = 1583291065;
//        String appName = "3WFhLgzE";
//        String streamName = "e4da3b7fbbce2345d7772b0674a318d5";
//        String uuid = "0";
////        int time = (int) (new Date().getTime() / 1000) + 259200;
//        int time = 1583291065 + 259200;
//        String md5key = String.format(MD5_KEY_FORMAT, appName, streamName+ ".m3u8", time, uuid, streamConfig.getLiveKey());
//        String url =  generateUrl(new Date(Long.valueOf("1583291065000")), new Date(Long.valueOf(endDate)), appName, streamName + ".m3u8", streamConfig.getLiveDomain(), streamConfig.getLiveKey(), 259200, HTTP_URL_FORMAT);
//        String url2 =  String.format(HTTP_URL_FORMAT, streamConfig.getLiveDomain(), appName, streamName + ".m3u8", time, uuid, DigestUtils.md5Hex(md5key.getBytes()));
//        
//        streamConfig.setLiveAuthTime(30 * 60);
//        String[] urls = StreamAddressUtils.generateLiveUrl(new Date(), null, "test", "test", streamConfig);
//        for(String url : urls)
//            System.out.println(url);

//        String dateStr = 1552015936 + "000";
//        Date date = new Date(Long.valueOf(dateStr));
//        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        System.out.println(df.format(date));
//
//        String[] casters = StreamAddressUtils.generateLiveUrl(new Date(), date, "caster", "4b73c41fab2f4d2099b3af8433a8a334", streamConfig);
//        for (String caster: casters) {
//            System.out.println(caster);
//        }

    }
}
