package com.cku.upyun;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.cku.core.ZAErrorCode;
import com.cku.util.DateUtils;
import com.cku.util.Debugger;
import com.cku.util.SysConfig;

public class VideoInfoService
{
	private static String s_ffmpegPath = null;//"C:/ffmpeg/bin/ffmpeg.exe";
	
//	public static void main(String[] args) {
//		try {
//			String time = getVideoTime("http://chongaibao.b0.upaiyun.com/cab_test/video/video/4839fc5e-d05f-4178-bb78-951509afc500.mp4");
//			System.out.println(time);
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//	}
	static
	{
		String toolDir = SysConfig.getInstance().getProperty("tool_dir");
		
		
		String os = System.getProperty("os.name");  
		if(os.toLowerCase().startsWith("win")){  
			s_ffmpegPath = toolDir + File.separator + "ffmpeg.exe";
		}else{
			s_ffmpegPath = toolDir + File.separator + "ffmpeg";
		}
	}
	
	public static VideoInfo getVideoRes(String fPath) throws Exception
	{
		ProcessBuilder pb = new ProcessBuilder(s_ffmpegPath, "-analyzeduration", "50M", "-i", fPath);
		
		Process p = pb.start();
		
		int resultCode = p.waitFor();
		Debugger.doAssert(resultCode == 1, ZAErrorCode.ZA_ERC_3RD, "ffmpeg execution '%s' returns value %d", fPath, resultCode);
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
		
		VideoInfo vi = new VideoInfo();
		
		while (true)
		{
			String s = bufferedReader.readLine();
			if (s == null)
			{
				break;
			}
			
			String[] splits = s.trim().split(" ");
			
			boolean streamFound = false, videoFound = false;
			boolean durationFound = false;
			for (int i = 0; i < splits.length; ++i)
			{
				String partition = splits[i].replace(',', ' ');
				partition = partition.trim();
				if (partition.equals("Stream")) streamFound = true;
				if (partition.equals("Video:")) videoFound = true;	
				if (partition.equals("Duration:")) durationFound = true;	
				
				String[] x = partition.split("x");
				if (x.length == 2 && streamFound && videoFound)
				{
					try
					{
						int x1 = Integer.parseInt(x[0]);
						int x2 = Integer.parseInt(x[1]);
						
						if (x1 > 0 && x1 <= 16384 && x2 > 0 && x2 <= 9216)
						{
							vi.vRes = x1 + "x" + x2;
						}
						else
						{
							/* Not a resolution property, Just ignore. */
							continue;
						}
					}
					catch (Exception e)
					{
						
					}
				}
			}
			
			if (durationFound)
			{
				String duration = splits[1];
				System.out.println(duration);
				Date dx = DateUtils.strToDate(duration, "HH:mm:ss.SS");
				
				Calendar c = Calendar.getInstance();
				c.setTime(dx);
				long time = 0;
				time = c.get(Calendar.HOUR);
				time = time * 60 + c.get(Calendar.MINUTE);
				time = time * 60 + c.get(Calendar.SECOND);
				time = time * 1000 + c.get(Calendar.MILLISECOND);
				
				vi.durationMS = time;
			}
		}

		Debugger.doAssert(vi.vRes != null && vi.durationMS != null, ZAErrorCode.ZA_ERC_INCOMPATABLE_FILE_FORMAT, 
				"Can't find resolution or duration of file %s", fPath);
		
		return vi;
	}
	
    /**
     * 获取视频总时间
     * @return
     */
    public static String getVideoTime(String video_path) {
        List<String> commands = new java.util.ArrayList<String>();
        commands.add(s_ffmpegPath);
        commands.add("-i");
        commands.add(video_path);
        try {
            ProcessBuilder builder = new ProcessBuilder();
            builder.command(commands);
            final Process p = builder.start();

            //从输入流中读取视频信息
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            StringBuffer sb = new StringBuffer();
            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();

            //从视频信息中解析时长
            String regexDuration = "Duration: (.*?), start: (.*?), bitrate: (\\d*) kb\\/s";
            Pattern pattern = Pattern.compile(regexDuration);
            Matcher m = pattern.matcher(sb.toString());
            if (m.find()) {
                String time = m.group(1);
                System.out.println(video_path+"===="+time+",视频时长："+time.substring(3,time.length()-3)+", 开始时间："+m.group(2)+",比特率："+m.group(3)+"kb/s");
                return time.substring(3,time.length()-3);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

//    //格式:"00:00:10.68"
//    private static int getTimelen(String timelen){
//        int min=0;
//        String strs[] = timelen.split(":");
//        if (strs[0].compareTo("0") > 0) {
//            min+=Integer.valueOf(strs[0])*60*60;//秒
//        }
//        if(strs[1].compareTo("0")>0){
//            min+=Integer.valueOf(strs[1])*60;
//        }
//        if(strs[2].compareTo("0")>0){
//            min+=Math.round(Float.valueOf(strs[2]));
//        }
//        return min;
//    }
}
