package com.xxrv.video.util;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;

import com.rv.component.dialog.DownloadLoadingDialog;
import com.xxrv.video.activity.TriListActivity;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/******
 * 下载视频
 */
public class DownloadVideo {
    private static DownloadVideo instance = null;

    private DownloadVideo() {
    }

    public static <T> DownloadVideo getInstance() {
        if (instance == null) {
            synchronized (DownloadVideo.class) {
                if (instance == null) {
                    instance = new DownloadVideo();
                }
            }

        }
        return instance;
    }


    public void downMp4(String url, Activity mActivity) {
        final DownloadLoadingDialog pd; // 进度条对话框
        pd = new DownloadLoadingDialog(mActivity);
        //设置点击屏幕不消失
        pd.setCanceledOnTouchOutside(false);
        //设置点击返回键不消失
        pd.setCancelable(false);
        pd.show();
        new Thread() {
            @Override
            public void run() {
                try {
                    File file = getFileFromServer(url, pd);

                    ContentResolver localContentResolver = mActivity.getContentResolver();
                    ContentValues localContentValues = getVideoContentValues(mActivity, file, System.currentTimeMillis());
                    Uri localUri = localContentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, localContentValues);
                    mActivity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri));

                    sleep(1000);
                    pd.dismiss(); // 结束掉进度条对话框
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 视频存在本地
     *
     * @param paramContext
     * @param paramFile
     * @param paramLong
     * @return
     */
    public static ContentValues getVideoContentValues(Context paramContext, File paramFile, long paramLong) {
        ContentValues localContentValues = new ContentValues();
        localContentValues.put("title", paramFile.getName());
        localContentValues.put("_display_name", paramFile.getName());
        localContentValues.put("mime_type", "video/3gp");
        localContentValues.put("datetaken", Long.valueOf(paramLong));
        localContentValues.put("date_modified", Long.valueOf(paramLong));
        localContentValues.put("date_added", Long.valueOf(paramLong));
        localContentValues.put("_data", paramFile.getAbsolutePath());
        localContentValues.put("_size", Long.valueOf(paramFile.length()));
        return localContentValues;
    }

    public File getFileFromServer(String path, DownloadLoadingDialog pd) throws Exception {
        // 如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            // 获取到文件的大小
//            pd.setMax(conn.getContentLength());
            InputStream is = conn.getInputStream();
            File sd1 = Environment.getExternalStorageDirectory();
            String path1 = sd1.getPath() + "/lfmf";
            File myfile1 = new File(path1);
            if (!myfile1.exists()) {
                myfile1.mkdir();
            }
            File file = new File(myfile1, System.currentTimeMillis() + ".mp4");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;
            Handler handler = new Handler(Looper.getMainLooper());
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
                handler.post(new ProgressUpdater(total, pd, conn.getContentLength()));
                // 获取当前下载量
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        } else {
            return null;
        }
    }


    private class ProgressUpdater implements Runnable {
        private int total;
        private DownloadLoadingDialog pd;
        private int contentLength;

        public ProgressUpdater(int total, DownloadLoadingDialog pd, int contentLength) {
            this.total = total;
            this.pd = pd;
            this.contentLength = contentLength;
        }

        @Override
        public void run() {
            int i = (int) (100 * total / contentLength);
            pd.setContent(i);
        }
    }
}
