package kr.co.compcarecompany.Activity;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import gun0912.tedimagepicker.builder.TedImagePicker;
import kr.co.compcarecompany.MyApplication;
import kr.co.compcarecompany.R;
import kr.co.compcarecompany.Util.FileUploadHelper;

public class WebviewAct  extends ActivityBasic {

    String Title = "";
    String url;

    WebView webView;

    ProgressBar progress;

    public ValueCallback<Uri> mUploadMessage;
    public ValueCallback<Uri[]> mFilePathCallback;
    public final static int FILECHOOSER_RESULTCODE = 1;
    public final static int PICK_IMAGE_REQ_CODE = 2;
    private Uri cameraImageUri = null;
    public final static String TYPE_IMAGE = "image/*";
    private String mCameraPhotoPath;

    public static final String INTENT_PROTOCOL_START = "intent:";
    public static final String INTENT_PROTOCOL_INTENT = "#Intent;";
    public static final String INTENT_PROTOCOL_END = ";end;";
    public static final String GOOGLE_PLAY_STORE_PREFIX = "market://details?id=";

    @Override
    protected void init() {
        progress = findViewById(R.id.progress);
        webView = findViewById(R.id.webView);
        Set_Webview();
    }

    void Set_Webview() {
        WebSettings settings = webView.getSettings();
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setBuiltInZoomControls(true);
        settings.setDisplayZoomControls(false);

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                Log.d("onGeolocation", "onGeolocationPermissionsShowPrompt");
                super.onGeolocationPermissionsShowPrompt(origin, callback);
                callback.invoke(origin, true, false);
            }

            @Override
            public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture, Message resultMsg) {
                Log.d("onCreateWindow", "onCreateWindow");
                WebView newWebView = new WebView(WebviewAct.this);

                WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
                transport.setWebView(newWebView);
                resultMsg.sendToTarget();

                return true;
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                Log.d("onJsAlert", url);
                /*new AlertDialog.Builder(view.getContext())
                        .setTitle(getString(R.string.app_name))
                        .setMessage(message)
                        .setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setCancelable(false)
                        .create()
                        .show();*/

                //Toast.makeText(context, message, Toast.LENGTH_LONG).show();
                return false;
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                Log.d("onJsConfirm", url);
                new AlertDialog.Builder(view.getContext())
                        .setTitle(getString(R.string.app_name))
                        .setMessage(message)
                        .setPositiveButton(android.R.string.ok,
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        result.confirm();
                                    }
                                })
                        .setNegativeButton(android.R.string.cancel,
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        result.cancel();
                                    }
                                })
                        .create()
                        .show();

                return true;
            }

            /**
             * 이미지 업로드(type=file 에서 호출되는 메서드)
             *
             * @param uploadMsg
             */
            // For Android Version < 3.0
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType(TYPE_IMAGE);
                startActivityForResult(Intent.createChooser(i, "파일 선택"), FILECHOOSER_RESULTCODE);
            }

            // For 3.0 <= Android Version < 4.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                openFileChooser(uploadMsg, acceptType, "");
            }

            // For 4.1 <= Android Version < 5.0
            public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType, String capture) {
                if (mFilePathCallback != null) {
                    mFilePathCallback.onReceiveValue(null);
                }
                mUploadMessage = uploadFile;
                imageChooser();
            }

            // For Android Version 5.0+
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                if (mFilePathCallback != null) {
                    mFilePathCallback.onReceiveValue(null);
                }
                mFilePathCallback = filePathCallback;
                imageChooser();
                return true;
            }

            public void imageChooser() {
                TedImagePicker.with(context)
                        .start(uri -> {
                            FileUploadHelper helper = new FileUploadHelper();
                            Uri[] u = new Uri[]{Uri.fromFile(helper.getResizeFile(uri))};
                            mFilePathCallback.onReceiveValue(u);
                            mFilePathCallback = null;
                        });
//                TedBottomPicker tedBottomPicker = new TedBottomPicker.Builder(WebviewAct.this).setImageProvider(new TedBottomPicker.ImageProvider() {
//                    @Override
//                    public void onProvideImage(ImageView imageView, Uri imageUri) {
//                        Glide.with(WebviewAct.this).load(imageUri).apply(RequestOptions.centerCropTransform()).into(imageView);
//                    }
//                }).setOnImageSelectedListener(new TedBottomPicker.OnImageSelectedListener() {
//                    @Override
//                    public void onImageSelected(Uri uri) {
//                        FileUploadHelper helper = new FileUploadHelper();
//                        Uri[] u = new Uri[]{Uri.fromFile(helper.getResizeFile(WebviewAct.this, uri.getPath()))};
//                        mFilePathCallback.onReceiveValue(u);
//                        mFilePathCallback = null;
//                    }
//                }).create();
//                tedBottomPicker.show(getSupportFragmentManager());
            }
        });

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                progress.setVisibility(View.VISIBLE);
            }

            //웹페이지 로딩 종료시 호출
            @Override
            public void onPageFinished(WebView view, String url) {
                progress.setVisibility(View.GONE);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                //view.loadUrl("about:blank"); // 빈페이지 출력
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });

                switch (errorCode) {
                    case ERROR_AUTHENTICATION: // 서버에서 사용자 인증 실패
                        builder.setMessage("서버에서 사용자 인증을 실패하였습니다.\nERROR_CODE : ERROR_AUTHENTICATION");
                        break;
                    case ERROR_BAD_URL: // 잘못된 URL
                        builder.setMessage("URL이 올바르지 않습니다.\nERROR_CODE : ERROR_BAD_URL");
                        break;
                    case ERROR_CONNECT: // 서버로 연결 실패
                        builder.setMessage("서버로 연결을 실패하였습니다.\nERROR_CODE : ERROR_CONNECT");
                        break;
                    case ERROR_FAILED_SSL_HANDSHAKE: // SSL handshake 수행 실패
                        builder.setMessage("SSL handshake 수행을 실패하였습니다..\nERROR_CODE : ERROR_FAILED_SSL_HANDSHAKE");
                        break;
                    case ERROR_FILE: // 일반 파일 오류
                        builder.setMessage("일반 파일 오류입니다.\nERROR_CODE : ERROR_FILE");
                        break;
                    case ERROR_FILE_NOT_FOUND: // 파일을 찾을 수 없습니다
                        builder.setMessage("파일을 찾을 수 없습니다.\nERROR_CODE : ERROR_FILE_NOT_FOUND");
                        break;
                    case ERROR_HOST_LOOKUP: // 서버 또는 프록시 호스트 이름 조회 실패
                        builder.setMessage("서버 또는 프록시 호스트 이름 조회를 실패하였습니다.\nERROR_CODE : ERROR_HOST_LOOKUP");
                        break;
                    case ERROR_IO: // 서버에서 읽거나 서버로 쓰기 실패
                        builder.setMessage("서버에서 읽거나 서버로 쓰기 실패하였습니다.\nERROR_CODE : ERROR_IO");
                        break;
                    case ERROR_PROXY_AUTHENTICATION: // 프록시에서 사용자 인증 실패
                        builder.setMessage("프록시 사용자 인증을 실패하였습니다.\nERROR_CODE : ERROR_PROXY_AUTHENTICATION");
                        break;
                    case ERROR_REDIRECT_LOOP: // 너무 많은 리디렉션
                        builder.setMessage("리디렉션을 초과하였습니다.\nERROR_CODE : ERROR_REDIRECT_LOOP");
                        break;
                    case ERROR_TIMEOUT: // 연결 시간 초과
                        builder.setMessage("연결 시간을 초과하였습니다.\nERROR_CODE : ERROR_TIMEOUT");
                        break;
                    case ERROR_TOO_MANY_REQUESTS: // 페이지 로드중 너무 많은 요청 발생
                        builder.setMessage("너무 많은 요청이 발생하였습니다.\nERROR_CODE : ERROR_TOO_MANY_REQUESTS");
                        break;
                    case ERROR_UNKNOWN: // 일반 오류
                        builder.setMessage("일반적 오류입니다.\nERROR_CODE : ERROR_UNKNOWN");
                        break;
                    case ERROR_UNSUPPORTED_AUTH_SCHEME: // 지원되지 않는 인증 체계
                        builder.setMessage("지원되지 않는 인증 체계입니다.\nERROR_CODE : ERROR_UNSUPPORTED_AUTH_SCHEME");
                        break;
                    case ERROR_UNSUPPORTED_SCHEME: // URI가 지원되지 않는 방식
                        builder.setMessage("URI가 지원되지 않는 방식입니다.\nERROR_CODE : ERROR_UNSUPPORTED_SCHEME");
                        break;
                    default:
                        builder.setMessage("원인을 알수 없는 오류입니다.\n네트워크 상태를 확인하시거나 나중에 다시 시도 해 주세요.\nERROR_CODE : ERROR_UNKNOWN");
                        break;
                }

                builder.setTitle(R.string.app_name);
                builder.setCancelable(false); // 뒤로가기 버튼 차단
                builder.show(); // 다이얼로그실행
            }

            public boolean shouldOverrideUrlLoading(WebView view, String overrideUrl) {
                Log.d("UrlLoading", overrideUrl);
                if (overrideUrl.startsWith(INTENT_PROTOCOL_START)) {
                    final int customUrlStartIndex = INTENT_PROTOCOL_START.length();
                    final int customUrlEndIndex = overrideUrl.indexOf(INTENT_PROTOCOL_INTENT);
                    if (customUrlEndIndex < 0) {
                        return false;
                    } else {
                        final String customUrl = overrideUrl.substring(customUrlStartIndex, customUrlEndIndex);
                        try {
                            getBaseContext().startActivity((new Intent(Intent.ACTION_VIEW, Uri.parse(customUrl))).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                        } catch (ActivityNotFoundException e) {
                            final int packageStartIndex = customUrlEndIndex + INTENT_PROTOCOL_INTENT.length();
                            final int packageEndIndex = overrideUrl.indexOf(INTENT_PROTOCOL_END);

                            final String packageName = overrideUrl.substring(packageStartIndex, packageEndIndex < 0 ? overrideUrl.length() : packageEndIndex);
                            getBaseContext().startActivity((new Intent(Intent.ACTION_VIEW, Uri.parse(GOOGLE_PLAY_STORE_PREFIX + packageName))).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                        }
                        return true;
                    }
                }
                if (overrideUrl.startsWith("https://")) {
                    return false;
                }
                return true;
            }
        });

        if (Build.VERSION.SDK_INT >= 21) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        webView.loadUrl(url);
    }

    @Override
    protected void init_Listener() {

    }

    @Override
    protected void getMessage(Message msg) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent intent = getIntent();
        Title = intent.getStringExtra("title");
        url = intent.getStringExtra("url");
        setContentView(R.layout.activity_webview, Title);
        MyApplication.myActivity = this;
        super.onCreate(savedInstanceState);
    }
}
