package com.cftech.core.util;

import it.sauronsoftware.jave.*;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 作者 lisw:
 * @version 创建时间：2016年11月28日 下午2:13:20
 *          类说明
 */
public class FileUtils {
    private static final String[] ALLOWED_EXT = new String[]{"gif", "jpeg", "jpg", "png", "psd", "bmp", "tiff", "tif", "swc", "jpc", "jp2", "jpx", "jb2", "xbm", "wbmp"};

    public static boolean isImage(File file) {
        List<String> list = Arrays.asList(ALLOWED_EXT);
        if(file != null) {
            return isImage(file.getName().toLowerCase());
        } else {
            return false;
        }
    }

    public static boolean isImage(String fileName) {
        List<String> list = Arrays.asList(ALLOWED_EXT);
        String fileExt = null;
        if(fileName != null &&StringUtils.isNotBlank(fileName)) {
            fileExt =  getFileExtension(fileName.toLowerCase());
            return fileExt != null?list.contains(fileExt):false;
        } else {
            return false;
        }
    }

    public static String getFileExtension(String fileName) {
        return fileName != null && fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != fileName.length() - 1?fileName.substring(fileName.lastIndexOf(".") + 1):null;
    }

    /**
     * 根据链接，获取链接返回的流
     */

    public static InputStream getInputStream(String sourceUrl) {
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;

        try {
            URL url = new URL(sourceUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            // 设置网络连接超时时间
            httpURLConnection.setConnectTimeout(3000);
            // 设置应用程序要从网络连接读取数据
            httpURLConnection.setDoInput(true);

            httpURLConnection.setRequestMethod("GET");
            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == 200) {
                // 从服务器返回一个输入流
                inputStream = httpURLConnection.getInputStream();

            }

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return inputStream;
    }



    public static Map<String,Object> getInputStreamMap(String sourceUrl) {
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;

        try {
            URL url = new URL(sourceUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            // 设置网络连接超时时间
            httpURLConnection.setConnectTimeout(3000);
            // 设置应用程序要从网络连接读取数据
            httpURLConnection.setDoInput(true);

            httpURLConnection.setRequestMethod("GET");
            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == 200) {
                // 从服务器返回一个输入流
                inputStream = httpURLConnection.getInputStream();
            }

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        Map<String,Object> params = new HashMap<String,Object>();

        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(inputStream);
            String type = HttpURLConnection.guessContentTypeFromStream(bis);

            InputStreamCache cache = new InputStreamCache(bis);
            params.put("inputstream",cache);
            params.put("type",FileType.get(type));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

        }
        return params;
    }


    /**
     * String  >>>> inputStream
     */
    public static ByteArrayInputStream strToInputStream(String str) {
        ByteArrayInputStream stream = new ByteArrayInputStream(str.getBytes());
        return stream;
    }

    /**
     * inputStream >>>> String
     */
    public static String inputStreamToStr(InputStream is) {
        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        try {
            while ((line = in.readLine()) != null) {
                buffer.append(line);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return buffer.toString();
    }

    /**
     * file >>>> inputStream
     */
    public InputStream inputStreamToFile(File file) {
        InputStream in = null;
        try {
            in = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return in;
    }


    /**
     * @throws FileNotFoundException inputStream >>>>file
     */
    public static void inputstreamToFile(InputStream ins, File file) throws FileNotFoundException {
        OutputStream os = new FileOutputStream(file);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void changeToMp3(String sourcePath, String targetPath) {
        File source = new File(sourcePath);
        File target = new File(targetPath);
        AudioAttributes audio = new AudioAttributes();
        Encoder encoder = new Encoder();
        audio.setCodec("libmp3lame");
        EncodingAttributes attrs = new EncodingAttributes();
        attrs.setFormat("mp3");
        attrs.setAudioAttributes(audio);
        try {
            encoder.encode(source, target, attrs);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InputFormatException e) {
            e.printStackTrace();
        } catch (EncoderException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Map<String,Object> params =   getInputStreamMap("http://mpt.135editor.com/mmbiz_png/WZIm2QYjmTNNJjibY6juicE0jmb9tr4tpwCF6euSK4t12phuKEryWX2Re597swM6Gia8mzXkuzfwmqtG8faoNFpsw/640?wx_fmt=png");
        System.out.println("11111");
//        changeToMp3("E:\\old.amr", "E:\\old.mp3");
        //getInputStreamMap("http://image3.135editor.com/cache/remote/aHR0cHM6Ly9tbWJpei5xbG9nby5jbi9tbWJpei95cVZBcW9adkRpYkhQTTRhbGtoWmlhd0dyWXBsODlUQ3hNYmliOUQza3ByeUNKaWNITkFwdER2dGZ1S2FjWEJKMk0xdU9SM0ZjcDFRdVJuRDJFUHhvd1VmRncvMA==");
    }

    public static byte[] instreamToByte(InputStream inputstream) {
        byte[] b = new byte[28];
        try {
            inputstream.read(b, 0, 28);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return b;
    }

}
 