package com.easemob.veckit.ui;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import androidx.fragment.app.FragmentActivity;

import com.easemob.veckit.R;
import com.easemob.veckit.utils.CloudCallbackUtils;
import com.hyphenate.chat.ChatClient;
import com.hyphenate.chat.EMFileMessageBody;
import com.hyphenate.chat.EMMessageBody;
import com.hyphenate.chat.EMVideoMessageBody;
import com.hyphenate.chat.Message;
import com.hyphenate.helpdesk.callback.Callback;
import com.hyphenate.util.EMLog;
import com.hyphenate.util.UriUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;

/**
 * 展示视频内容
 *
 */
public class ShowVideoActivity extends FragmentActivity {
    private static final String TAG = "ShowVideoActivity";

    private RelativeLayout loadingLayout;
    private ProgressBar progressBar;
    private Uri localFilePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.vec_showvideo_activity);
        loadingLayout = (RelativeLayout) findViewById(R.id.loading_layout);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        final Message message = getIntent().getParcelableExtra("msg");

        CloudCallbackUtils.newCloudCallbackUtils().onCloseView();

        EMVideoMessageBody messageBody = (EMVideoMessageBody)message.body();


        localFilePath = messageBody.getLocalUri();
        EMLog.d(TAG, "localFilePath = "+localFilePath);
        EMLog.d(TAG, "local filename = "+messageBody.getFileName());

        if(UriUtils.isFileExistByUri(this, localFilePath)) {
            LocalVideoPlayerActivity.actionStart(this, localFilePath.toString());
            finish();
        } else {
            EMLog.d(TAG, "download remote video file");
            downloadVideo(message);
        }
    }


    private void showLocalVideo(final Message message) {
        EMVideoMessageBody messageBody = (EMVideoMessageBody)message.body();

        localFilePath = messageBody.getLocalUri();
        EMLog.d(TAG, "localFilePath = "+localFilePath);
        EMLog.d(TAG, "local filename = "+messageBody.getFileName());

        if(UriUtils.isFileExistByUri(this, localFilePath)) {
            LocalVideoPlayerActivity.actionStart(this, localFilePath.toString());
        } else {
            EMLog.e(TAG, "video file does not exist");
        }

        finish();
    }

    /**
     * 下载视频文件
     */
    private void downloadVideo(final Message message) {
        loadingLayout.setVisibility(View.VISIBLE);
	    message.setMessageStatusCallback(new Callback() {
            @Override
            public void onSuccess() {
                EMMessageBody body = message.body();
                if (body instanceof EMFileMessageBody){
                    EMFileMessageBody by = (EMFileMessageBody) body;
                    String localUrl = by.getLocalUrl();
                    saveVideoToAlbum(getApplicationContext(), localUrl,by.getFileName());
                }


                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        loadingLayout.setVisibility(View.GONE);
                        progressBar.setProgress(0);

                        showLocalVideo(message);
                    }
                });
            }

            @Override
            public void onError(int code, String error) {
                Log.e(TAG, "offline file transfer error:" + error);
                Uri localFilePath = ((EMVideoMessageBody) message.getBody()).getLocalUri();
                String filePath = UriUtils.getFilePath(ShowVideoActivity.this, localFilePath);
                if(TextUtils.isEmpty(filePath)) {
                    getContentResolver().delete(localFilePath, null, null);
                }else {
                    File file = new File(filePath);
                    if (file.exists()) {
                        file.delete();
                    }
                }
            }

            @Override
            public void onProgress(final int progress, String status) {
                Log.d(TAG, "video progress:" + progress);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressBar.setProgress(progress);
                    }
                });
            }
        });
        ChatClient.getInstance().vecChatManager().downloadAttachment(message);
    }

    @Override
    public void onBackPressed() {
        finish();
    }


    /**
     * 将视频保存到系统相册
     */
    public static boolean saveVideoToAlbum(Context context, String videoFile, String videoName) {
        Log.d(TAG, "saveVideoToAlbum() videoFile = [" + videoFile + "]");
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            return saveVideoToAlbumBeforeQ(context, videoFile, videoName);
        } else {
            return saveVideoToAlbumAfterQ(context, videoFile, videoName);
        }
    }

    private static boolean saveVideoToAlbumAfterQ(Context context, String videoFile, String videoName) {
        try {
            ContentResolver contentResolver = context.getContentResolver();
            File tempFile = new File(videoFile);
            ContentValues contentValues = getVideoContentValues(context, tempFile, System.currentTimeMillis(), videoName);
            Uri uri = contentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, contentValues);
            copyFileAfterQ(context, contentResolver, tempFile, uri);
            contentValues.clear();
            contentValues.put(MediaStore.MediaColumns.IS_PENDING, 0);
            context.getContentResolver().update(uri, contentValues, null, null);

            MediaScannerConnection.scanFile(context,
                    new String[]{videoFile},
                    null, null);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private static boolean saveVideoToAlbumBeforeQ(Context context, String videoFile, String videoName) {
        File destFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        if (!destFile.exists()){
            destFile.mkdirs();
        }
        destFile = new File(destFile, videoName);
        if (destFile.exists()){
            destFile.delete();
        }

        File tempFile = new File(videoFile);
        FileInputStream ins = null;
        BufferedOutputStream ous = null;
        try {
            ins = new FileInputStream(tempFile);
            ous = new BufferedOutputStream(new FileOutputStream(destFile));
            byte[] buf = new byte[1024];
            int n;
            while ((n = ins.read(buf)) > 0) {
                ous.write(buf, 0, n);
            }
            /*MediaScannerConnection.scanFile(
                    context,
                    new String[]{destFile.getAbsolutePath()},
                    new String[]{"video/*"},
                    (path, uri) -> {
                        com.hyphenate.helpdesk.util.Log.d(TAG, "saveVideoToAlbum: " + path + " " + uri);
                        // Scan Completed
                    });*/
            MediaScannerConnection.scanFile(context,
                    new String[]{videoFile},
                    null, null);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (ins != null) {
                    ins.close();
                }
                if (ous != null) {
                    ous.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void copyFileAfterQ(Context context, ContentResolver localContentResolver, File tempFile, Uri localUri) throws IOException {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q /*&&
                context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.Q*/) {
            //拷贝文件到相册的uri,android10及以上得这么干，否则不会显示。可以参考ScreenMediaRecorder的save方法
            OutputStream os = localContentResolver.openOutputStream(localUri);
            Files.copy(tempFile.toPath(), os);
            os.close();
            // tempFile.delete();
        }
    }

    /**
     * 获取视频的contentValue
     */
    public static ContentValues getVideoContentValues(Context context, File paramFile, long timestamp, String videoName) {
        ContentValues localContentValues = new ContentValues();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            localContentValues.put(MediaStore.Video.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
        }
        localContentValues.put(MediaStore.Video.Media.TITLE, videoName);
        localContentValues.put(MediaStore.Video.Media.DISPLAY_NAME, videoName);
        localContentValues.put(MediaStore.Video.Media.MIME_TYPE, "video/*");
        localContentValues.put(MediaStore.Video.Media.DATE_TAKEN, timestamp);
        localContentValues.put(MediaStore.Video.Media.DATE_MODIFIED, timestamp);
        localContentValues.put(MediaStore.Video.Media.DATE_ADDED, timestamp);
        localContentValues.put(MediaStore.Video.Media.SIZE, paramFile.length());
        return localContentValues;
    }
}
