package kr.co.hanwha.hifive.screen.common;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.HashMap;

import kr.co.hanwha.hifive.R;
import kr.co.hanwha.hifive.base.BaseActivity;
import kr.co.hanwha.hifive.dialog.HFSingleDialog;
import kr.co.hanwha.hifive.enums.BaseAnimationType;
import kr.co.hanwha.hifive.enums.BaseToolbarType;
import kr.co.hanwha.hifive.util.HFActivityUtil;
import kr.co.hanwha.hifive.util.HFConstants;
import kr.co.hanwha.hifive.util.HFInfoUtil;

/**
 * Created by sanghoonkwon on 2018. 2. 7..
 */

public class CommonWebViewActivity extends BaseActivity {
    private RelativeLayout mLayoutToolbar;
    private TextView mTextViewTitle;
    private TextView mTextViewSubTitle;
    private LinearLayout mLayoutBottom;
    private ImageButton mImageButtonPre;
    private ImageButton mImageButtonNext;

    private WebView mWebView;

    private String mUrl;
    private HashMap<String, String> mHeader;

    @Override
    protected int getContentViewResource() {
        return R.layout.activity_common_webview;
    }

    @Override
    protected BaseToolbarType isToolbarStyle() {
        return null;
    }

    @Override
    protected BaseAnimationType isShowActivityAnimation() {
        return BaseAnimationType.RIGHT;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mUrl = getIntent().getStringExtra(HFActivityUtil.INTENT_URL);

        mLayoutToolbar = (RelativeLayout) findViewById(R.id.toolbar_relativeLayout);
        mTextViewTitle = (TextView) findViewById(R.id.title_textView);
        mTextViewSubTitle = (TextView) findViewById(R.id.subTitle_textView);
        mLayoutBottom = (LinearLayout) findViewById(R.id.bottom_linearLayout);
        mImageButtonPre = (ImageButton) findViewById(R.id.pre_imageButton);
        mImageButtonNext = (ImageButton) findViewById(R.id.next_imageButton);

//        mLoadingDialog.setCancelable(true);

        mTextViewSubTitle.setText(mUrl);

        (findViewById(R.id.share_imageButton)).setVisibility(getIntent().getBooleanExtra(HFActivityUtil.INTENT_VISIBLE_SHARE, false) ? View.VISIBLE : View.GONE);
        mTextViewTitle.setVisibility(getIntent().getBooleanExtra(HFActivityUtil.INTENT_VISIBLE_TITLE, false) ? View.VISIBLE : View.GONE);
        mTextViewSubTitle.setVisibility(getIntent().getBooleanExtra(HFActivityUtil.INTENT_VISIBLE_SUBTITLE, false) ? View.VISIBLE : View.GONE);

        findViewById(R.id.back_imageButton).setOnClickListener(onClickListener);
        findViewById(R.id.share_imageButton).setOnClickListener(onClickListener);
        findViewById(R.id.pre_imageButton).setOnClickListener(onClickListener);
        findViewById(R.id.next_imageButton).setOnClickListener(onClickListener);

        mWebView = (WebView) findViewById(R.id.webView);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebViewClient(new CommonWebViewClient());
        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.addJavascriptInterface(new HFJavaScript(), "Android");

        String param = "";
        String encryption = getIntent().getStringExtra(HFActivityUtil.INTENT_ENCRYPTION);
        if (TextUtils.isEmpty(encryption) == false) {
            param += (TextUtils.isEmpty(param) ? "?" : "&") + HFConstants.HEADER_ENCRYPTION_MEMBER_ID + "=" + encryption;
        }

        int project_id = getIntent().getIntExtra(HFActivityUtil.INTENT_PROJECT_ID, 0);
        if (project_id != 0) {
            param += (TextUtils.isEmpty(param) ? "?" : "&") + HFConstants.HEADER_PROJECT_ID + "=" + project_id;
        }

        String department = HFInfoUtil.getDepartmentValue(this);
        if (TextUtils.isEmpty(department) == false) {
            mHeader = new HashMap<>();
            mHeader.put(HFConstants.HEADER_USER_TYPE, department);
        }

        mUrl += param;
        if (TextUtils.isEmpty(mUrl) == false) {
            if (mUrl.toLowerCase().startsWith("http") == false) mUrl = "http://" + mUrl;

//            /*
            if (mHeader != null)
                mWebView.loadUrl(mUrl, mHeader);
            else mWebView.loadUrl(mUrl);
//            */
            /*
            if (mHeader != null) {
                String postData = "";
                for (String key : mHeader.keySet()) {
                    if (TextUtils.isEmpty(postData) == false)
                        postData += "&";
                    postData += key + "=" + mHeader.get(key);
                }
                mWebView.postUrl(mUrl, postData.getBytes());
            } else {
                mWebView.postUrl(mUrl, null);
            }
            */
        } else {
            showAlert(getString(R.string.alert_default_title), getString(R.string.alert_default_message),
                    new HFSingleDialog.OnDialogCallback() {
                        @Override
                        public void onPositive() {
                            finish();
                        }
                    });
        }
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack())
            mWebView.goBack();
        else
            super.onBackPressed();
    }

    /**************************************************
     * Support methods
     **************************************************/
    private void checkBottomLayout() {
        if (mWebView.canGoBack() || mWebView.canGoForward()) {
            mLayoutBottom.setVisibility(View.VISIBLE);
            mImageButtonPre.setEnabled(mWebView.canGoBack());
            mImageButtonPre.setAlpha(mWebView.canGoBack() ? 1.0f : 0.3f);
            mImageButtonNext.setEnabled(mWebView.canGoForward());
            mImageButtonNext.setAlpha(mWebView.canGoForward() ? 1.0f : 0.3f);
        } else {
            mLayoutBottom.setVisibility(View.GONE);
        }
    }

    /**************************************************
     * WebViewClient
     **************************************************/
    public class HFJavaScript {
        public HFJavaScript() {
        }

        @JavascriptInterface
        public void openCustomPopup(String title, String message) {
            showAlert(title, message, new HFSingleDialog.OnDialogCallback() {
                @Override
                public void onPositive() {
                    //...
                }
            });
        }

        @JavascriptInterface
        public void openCustomPopup(String message) {
            showAlert(getString(R.string.alert_default_title), message, new HFSingleDialog.OnDialogCallback() {
                @Override
                public void onPositive() {
                    //...
                }
            });
        }

        @JavascriptInterface
        public void closeWebview() {
            finish();
        }

        @JavascriptInterface
        public void showToast(String type, String content) {

            if (TextUtils.isEmpty(content)) return;
            int icon = 1;
            try {
                icon = Integer.parseInt(type);
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (icon == 1)
                showToastAlert(content);
            else if (icon == 2)
                showToastEmpty(content);
            else if (icon == 3)
                showToastConfirm(content);
            else if (icon == 4)
                showToastImpossible(content);
            else
                showToastAlert(content);
        }
    }

    /**************************************************
     * WebViewClient
     **************************************************/
    public class CommonWebViewClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            /*
            if (TextUtils.isEmpty(url) == false && url.equals(mUrl) == false && mHeader != null) {
                mWebView.loadUrl(url, mHeader);
                mUrl = url;
            } else {
                mUrl = url;
                super.onPageStarted(view, url, favicon);
            }
            */
            super.onPageStarted(view, url, favicon);
            showLoadingDialog(true);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

            mUrl = url;//TODO- CHECK

            showLoadingDialog(false);
            mTextViewTitle.setText(view.getTitle());
            checkBottomLayout();
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            showLoadingDialog(false);
        }

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);
            showLoadingDialog(false);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
//            return true;
        }
    }

    /**************************************************
     * View.OnClickListener
     **************************************************/
    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.back_imageButton:
                    finish();
                    break;
                case R.id.share_imageButton:
                    try {
                        HFActivityUtil.startUrl(CommonWebViewActivity.this, mUrl);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case R.id.pre_imageButton:
                    if (mWebView.canGoBack()) mWebView.goBack();
                    break;
                case R.id.next_imageButton:
                    if (mWebView.canGoForward()) mWebView.goForward();
                    break;
            }
        }
    };
}
