package com.steps.tmuapp;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.PermissionRequest;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.steps.tmuapp.lib.FileChooser;

import java.io.File;

import static com.steps.tmuapp.lib.Permissions.CHOOSE_FILE_REQUEST;
import static com.steps.tmuapp.lib.VersionUtils.checkAndRequestCameraPermissionAbove23;


public class MyWebChromeClient extends WebChromeClient {
    private final static String TAG = "MyWebChromeClient";
    private MainActivity mActivity;
    private ProgressBar mProgressBar;

    MyWebChromeClient(MainActivity activity, ProgressBar progressBar) {
        mActivity = activity;
        mProgressBar = progressBar;
    }

    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        super.onProgressChanged(view, newProgress);
        mProgressBar.setProgress(newProgress);
        if (newProgress != 100) {
            mProgressBar.setVisibility(View.VISIBLE);
        } else {
            mProgressBar.setVisibility(View.GONE);
        }
    }

    @Override
    public void onGeolocationPermissionsHidePrompt() {
        super.onGeolocationPermissionsHidePrompt();
        Log.i(TAG, "onGeolocationPermissionsHidePrompt");
    }

    @Override
    public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
        Log.d(TAG, consoleMessage.message() + " -- From line "
                + consoleMessage.lineNumber() + " of "
                + consoleMessage.sourceId());
        return super.onConsoleMessage(consoleMessage);
    }

    // For Android >= 5.0
    @Override
    public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
        if (checkAndRequestCameraPermissionAbove23(mActivity)) {
            FileChooser.filePathCallback = filePathCallback;
            openImageChooserActivity();
            return true;
        } else {
            Toast.makeText(mActivity, "請先開啟相機及儲存裝置權限",
                    Toast.LENGTH_LONG).show();
            return false;
        }
    }

    /**
     * 上傳頭像時的彈出框
     */
    private void openImageChooserActivity() {
        new AlertDialog.Builder(mActivity)
                .setTitle("更改頭像")
                .setItems(new String[]{"拍照", "相簿選取"},
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                switch (which) {
                                    case 0:
                                        createCameraIntent(mActivity);

                                        break;
                                    case 1:
                                        Intent i = createFileItent();
                                        mActivity.startActivityForResult(Intent.createChooser(i, "Image Chooser"), CHOOSE_FILE_REQUEST);
                                        break;
                                }
                            }
                        }).setNegativeButton("取消", null).show();
    }

    /**
     * 建立選擇相簿的intent
     *
     * @return intent
     */
    private Intent createFileItent() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        Intent intent = new Intent(
                Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setDataAndType(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                "image/*");
        return intent;
    }

    /**
     * 建立呼叫照相機的intent
     */
    private void createCameraIntent(Activity activity) {
        checkAndRequestCameraPermissionAbove23(mActivity);
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (checkAndRequestCameraPermissionAbove23(mActivity)) {
            if (cameraIntent.resolveActivity(activity.getPackageManager()) != null) {
                File externalDataDir = Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                File cameraDataDir = new File(externalDataDir.getAbsolutePath()
                        + File.separator + "browser-photo");
                cameraDataDir.mkdirs();
                File newFile = new File(cameraDataDir, System.currentTimeMillis() + ".jpg");
                Uri phtoUri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".provider", newFile);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, phtoUri);
                cameraIntent.putExtra("PhotoPath", phtoUri);
                FileChooser.cameraPhotoUri = phtoUri;
                mActivity.startActivityForResult(Intent.createChooser(cameraIntent, "Take a picture"), CHOOSE_FILE_REQUEST);
            }
        }
    }

    @Override
    public void onPermissionRequest(PermissionRequest request) {
        super.onPermissionRequest(request);
    }
}