package com.wisedu.coeus.util;

import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.MultimediaInfo;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wisedu.coeus.core.ConstantStatic;
import com.wisedu.mooc.app.upload.RsConstant;

/**
 * Created by 01112026 on 14-7-29.
 */
public class FileUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class);

    /**
     * 安全关闭输入流
     *
     * @param inputStream
     */
    public static void closeStream(InputStream inputStream) {
        if (inputStream == null) return;
        try {
            inputStream.close();
        } catch (IOException e) {

        }
    }

    /**
     * 安全关闭输出流
     *
     * @param outputStream
     */
    public static void closeStream(OutputStream outputStream) {
        if (outputStream == null) return;
        try {
            outputStream.close();
        } catch (IOException e) {

        }
    }

    /**
     * 把输入流写入到文件内
     * @param inputStream
     * @param file
     * @throws IOException
     */
    public static void copyInputStreamToFile(InputStream inputStream, File file) throws IOException {
        org.apache.commons.io.FileUtils.copyInputStreamToFile(inputStream, file);
    }

    /**
     * 把文件移动到目标文件
     * @param filePath 当前目录文件
     * @param dirPath  目标目录文件
     * @throws IOException
     */
    public static void moveFile(File filePath, File dirPath) throws IOException {
        org.apache.commons.io.FileUtils.moveFile(filePath, dirPath);
    }

    public static void copyFile(File filePath, File dirPath) throws IOException {
        org.apache.commons.io.FileUtils.copyFile(filePath, dirPath);
    }

    /**
     * 删除单个文件
     *
     * @param sPath 被删除文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 删除目录（文件夹）以及目录下的文件
     *
     * @param sPath 被删除目录的文件路径
     * @return 目录删除成功返回true，否则返回false
     */
    public static boolean deleteDirectory(String sPath) {
        //如果sPath不以文件分隔符结尾，自动添加文件分隔符
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        //如果dir对应的文件不存在，或者不是一个目录，则退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        boolean flag = true;
        //删除文件夹下的所有文件(包括子目录)
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            //删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) break;
            } //删除子目录
            else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) break;
            }
        }
        if (!flag) return false;
        //删除当前目录
        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
    }

    public static List<String> listFiles(String dirPath, String baseRoot) {
        if (dirPath.endsWith("/")) {
            dirPath = dirPath.substring(0, dirPath.length() - 1);
        }
        if (!dirPath.startsWith("/")) {
            dirPath = "/" + dirPath;
        }
        List<String> fileList = new ArrayList<String>();
        File dir = new File(baseRoot.concat(dirPath));
        String rName;
        if (dir.exists() && dir.isDirectory()) {
            File[] subFile = dir.listFiles();
            for (File sub : subFile) {
                if (sub.exists()) {
                    rName = dirPath.concat("/").concat(sub.getName());
                    if (sub.isFile()) {
                        fileList.add(rName);
                    } else if (sub.isDirectory()) {
                        fileList.addAll(listFiles(rName, baseRoot));
                    }
                }
            }
        }
        return fileList;
    }


    /**
     * 抓取视频时长
     * @param filePath
     * @return
     */
    public static Long getVideoDuration(String filePath){
    	
    	filePath = ConstantStatic.RESOURCE_PATH + filePath;
    	File file = new File(filePath); 
    	Long ls = 0L;
    	if(!file.exists()){
    		return ls;
    	}
    	String fileName=file.getName(); 
    	
    	if(fileName.indexOf(".") == -1){
    		return ls;
    	}
    	
    	String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
    	if(!RsConstant.VIDEO_SUFFIX_LOCAL.contains(prefix)){
    		return ls;
    	}
    	try { 
    		Encoder encoder = new Encoder();  
            // 获取多媒体信息对象   
            MultimediaInfo m = encoder.getInfo(file);  
            // 调用方法获取时长   
            ls = m.getDuration();  
        } catch (Exception e) {  
        	LOGGER.error(e.getMessage(), e); 
        }  
    	return ls;
    }
    
    public static String getExtNameWidthDot(String filePath) {
        if (filePath == null) return "";
        int pos = filePath.lastIndexOf(".");
        if (pos == -1) return "";

        return filePath.substring(pos);
    }
    
    
    public static String getExtName(String filePath) {
        String ext = getExtNameWidthDot(filePath);
        return ext.length()==0?ext:ext.substring(1);
    }
    
    public static String getContentTypeByFileExt(final String filenameExtension) {
        if (filenameExtension.equalsIgnoreCase("ASF")) {
            return "video/x-ms-asf";
        }
        if (filenameExtension.equalsIgnoreCase("AVI") ) {
            return "video/x-msvideo";
        }
        if (filenameExtension.equalsIgnoreCase("MP4") ) {
            return "video/mp4";
        }
        if (filenameExtension.equalsIgnoreCase("MPE") ) {
            return "video/x-mpeg";
        }
        if (filenameExtension.equalsIgnoreCase("MPEG")|| filenameExtension.equalsIgnoreCase("MPG") ) {
            return "video/mpeg";
        }
        if (filenameExtension.equalsIgnoreCase("WM") || filenameExtension.equals("wm")) {
            return "video/x-ms-wm";
        }
        if (filenameExtension.equalsIgnoreCase("WMV")) {
            return "video/x-ms-wmv";
        }
        if (filenameExtension.equalsIgnoreCase("RMVB")) {
            return "application/vnd.rn-realmedia-vbr";
        }
        if (filenameExtension.equalsIgnoreCase("PDF")) {
            return "application/pdf";
        }
        if (filenameExtension.equalsIgnoreCase("BMP")) {
            return "image/bmp";
        }
        if (filenameExtension.equalsIgnoreCase("GIF")) {
            return "image/gif";
        }
        if (filenameExtension.equalsIgnoreCase("JPEG")
                || filenameExtension.equalsIgnoreCase("JPG")
                || filenameExtension.equalsIgnoreCase("PNG") ) {
            return "image/jpeg";
        }
        if (filenameExtension.equalsIgnoreCase("HTML")
                || filenameExtension.equalsIgnoreCase("HTM")
                || filenameExtension.equalsIgnoreCase("SHTML")) {
            return "text/html";
        }
        if (filenameExtension.equalsIgnoreCase("TXT")) {
            return "text/plain";
        }
        if (filenameExtension.equalsIgnoreCase("VSD")) {
            return "application/vnd.visio";
        }
        if (filenameExtension.equalsIgnoreCase("PPTX")){
            return "application/vnd.openxmlformats-officedocument.presentationml.presentation";
        }

        if(filenameExtension.equalsIgnoreCase("PPT")){
            return "application/vnd.ms-powerpoint";
        }
        if (filenameExtension.equalsIgnoreCase("DOCX")){
            return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        }

        if(filenameExtension.equalsIgnoreCase("DOC")) {
            return "application/msword";
        }
        if (filenameExtension.equalsIgnoreCase("XML")) {
            return "text/xml";
        }
        return "application/octet-stream";
    }
    
}
