package com.hainaos.vc.utils;

import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class VideoUtils {
    public static String getFileNamefromURL(String url) {
        int position = url.lastIndexOf("/");
        return url.substring(position + 1);
    }

    public static String getFileNameWithoutExtension(String path) {
        String name = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf("."));
        Log.e("getFileName", "Name: " + name);
        return name;
    }

    public static boolean isUrl(String str) {
        String pattern = "(http|https|ftp)://((((25[0-5])|(2[0-4]\\d)|(1\\d{2})|([1-9]?\\d)\\.){3}((25[0-5])|(2[0-4]\\d)|(1\\d{2})|([1-9]?\\d)))|(([\\w-]+\\.)+(net|com|org|gov|edu|mil|info|travel|pro|museum|biz|[a-z]{2})))(/[\\w\\-~#]+)*(/[\\w-]+\\.[\\w]{2,4})?([\\?=&%_]?[\\w-]+)*";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(str);
        boolean matches = m.find();
        return matches;
    }

    private static final String[] video_extension = new String[]{
            ".3gp", ".avi", ".flv", ".mkv", ".mov", ".mp4", ".webm"
    };

    private static final String[] picture_extension = new String[]{
            ".jgp", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".jpe"
    };

    public static boolean isVideoFormat(String filePath) {
        for (String s : video_extension) {
            if (filePath.endsWith(s)) {
                return true;
            }
        }
        return false;
    }

    public static boolean isPicFormat(String filePath) {
        for (String s : picture_extension) {
            if (filePath.endsWith(s)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取单个文件的MD5值
     *
     * @param file 文件
     * @return
     */

    public static String getFileMD5s(File file) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        BigInteger bigInt = new BigInteger(1, digest.digest());
        return bigInt.toString(32);
    }

}
