package com.dahamit.dahammall;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebBackForwardList;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;

import com.dahamit.dahammall.config.URLConfig;
import com.dahamit.dahammall.util.PreferManager;
import com.dahamit.dahammall.util.Util;
import com.google.firebase.iid.FirebaseInstanceId;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {


    private static String TAG = "MainActivity";

    private RelativeLayout activity_main;

    private WebView thisWebView;
    private MyWebChromeClient chromWebclient;
    private ProgressDialog loading_dialog;
    private Context currContext;



    private ValueCallback<Uri> filePathCallbackNormal;
    private ValueCallback<Uri[]> filePathCallbackLollipop;
    private final static int FILECHOOSER_NORMAL_REQ_CODE = 1;
    private final static int FILECHOOSER_LOLLIPOP_REQ_CODE = 2;

    private String mCM;

    private ValueCallback mUM;
    private ValueCallback<Uri[]> mUMA;
    private final static int FCR=1;

    //select whether you want to upload multiple files
    private boolean multiple_files = false;


    private Uri mCapturedImageURI;



    private static String currentUrl = "";
    private static boolean isCall = false;


    String targeturl = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        activity_main = (RelativeLayout)this.findViewById(R.id.activity_main);

        Log.d("firebase", "onCreate - targeturl > "+targeturl);

        currContext = this;
        targeturl = URLConfig.CONTENT_URL_MAIN;
        loading_dialog = new ProgressDialog(this);
        loading_dialog.setMessage("Loading..");
        initWebView();


//        final MyAsyncTask downloadTask = new MyAsyncTask();
        //      downloadTask.execute();

    }

    @Override
    protected void onResume() {
        super.onResume();

        PreferManager.savePreferences(this,"pushCount","0");
        Intent badgeIntent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");

        badgeIntent.putExtra("badge_count", 0);
        badgeIntent.putExtra("badge_count_package_name", getPackageName());
        // badgeIntent.putExtra("badge_count_class_name", get());
        sendBroadcast(badgeIntent);

    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @SuppressLint("JavascriptInterface")
    public void initWebView(){

        thisWebView = (WebView)this.findViewById(R.id.thisWebView);

        thisWebView.getSettings().setJavaScriptEnabled(true);
        thisWebView.setVerticalScrollBarEnabled(true);
        thisWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        thisWebView.getSettings().setSupportMultipleWindows(true);

        thisWebView.getSettings().setAppCacheEnabled(true);
        thisWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        thisWebView.getSettings().setBuiltInZoomControls(false);
        thisWebView.getSettings().setGeolocationEnabled(true);

        thisWebView.getSettings().setSupportZoom(false);
        thisWebView.getSettings().setBlockNetworkImage(false);
        thisWebView.getSettings().setLoadsImagesAutomatically(true);
        thisWebView.getSettings().setAllowContentAccess(true);
        thisWebView.getSettings().setUseWideViewPort(true);
        thisWebView.getSettings().setLoadWithOverviewMode(true);
        thisWebView.getSettings().setDomStorageEnabled(true);


        thisWebView.getSettings().setAllowFileAccessFromFileURLs(true); //Maybe you don't need this rule
        thisWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);

        //웹뷰 성능 개선 코드
        thisWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        thisWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);


        thisWebView.getSettings().setSavePassword(false);
        thisWebView.setDownloadListener(new DownloadListener() {
            public void onDownloadStart(String url, String userAgent,
                                        String contentDisposition, String mimetype,
                                        long contentLength) {
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url));
                startActivity(i);
            }
        });

        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);

        thisWebView.setWebViewClient(new MyWebViewClient());
        chromWebclient = new MyWebChromeClient();
        thisWebView.setWebChromeClient(chromWebclient);

        thisWebView.addJavascriptInterface(new CustomJavascriptInterface(), "HybridApp");
        thisWebView.loadUrl(targeturl);
    }

    @SuppressLint("SetJavaScriptEnabled")
    public class CustomJavascriptInterface {

        @JavascriptInterface
        public void requestToken(String json) {
            Log.d("json","usrid>>>"+json);
            try {
            //    JSONObject jobject = new JSONObject(json);   // JSONArray 생성
            //    String user_id = jobject.getString("user_id");
                String user_id = json;
                Log.d("json","usrid"+user_id);
                PreferManager.savePreferences(currContext,"userid",user_id);
                String refreshedToken = FirebaseInstanceId.getInstance().getToken();
                Log.d("json","refreshedToken>>>"+refreshedToken);

                final String scriptStr = "javascript:setToken('android','"+user_id+"','"+refreshedToken+"');";
                Log.e("json","login 2 "+scriptStr);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        thisWebView.loadUrl(scriptStr);

                    }
                });

       //     } catch (JSONException e) {
         //       Log.e("json","error"+e);
         //       e.printStackTrace();
            }catch(Exception e){
                Log.e("json","Exception "+e);
            }
        }
    }


    private class MyWebViewClient extends WebViewClient
    {
        public boolean shouldOverrideUrlLoading(final WebView view,final String url) {
            Log.e("json","in shouldOverrideUrlLoading =>"+url);


            if(!Util.isNetWork(currContext)){
                Intent intent = new Intent(MainActivity.this, NoWifiActivity.class);

                startActivity(intent);
                finish();
            }else if ( url.startsWith("mailto:") || url.startsWith("tel:")  ) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
            }else{
                new Handler().post(new Runnable() {
                    public void run() {

                        view.loadUrl( url );

                    }
                });

                if (url.indexOf("usertel") >0) {

                    int idxs = url.indexOf("usertel");
                    final String userTel = url.substring(idxs+8);


                    if(url.indexOf("message")>0){
                        final int idxm = url.indexOf("message");
                        final String message = url.substring(idxm+8);
                        Log.e("WEB", "message >> "+ message);

                        try{
                            final String decodeResult = URLDecoder.decode(message, "UTF-8");

                            Log.e("WEB", "decodeResult >> "+decodeResult);
                            new Handler().post(new Runnable() { // new Handler and Runnable
                                @Override
                                public void run() {


                                }
                            });

                        }catch(Exception e){
                            Log.e("WEB", "decodeResult > "+e);

                        }

                    }

                }

                return(true);
            }

            return(true);
        }

        public void onPageFinished(WebView view, String url) {
            runOnUiThread(new Runnable(){
                public void run() {
                    loading_dialog.dismiss();
                }
            });

            super.onPageFinished(view, url);
        }
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            runOnUiThread(new Runnable(){
                public void run() {
                    loading_dialog.show();
                }
            });
            super.onPageStarted(view, url, favicon);
        }
    }
    final private class MyWebChromeClient extends android.webkit.WebChromeClient
    {
        public boolean onConsoleMessage(ConsoleMessage cm) {
            Log.e("WEB", cm.message() + " -- From line " + cm.lineNumber() + " of "  + cm.sourceId() );
            return true;
        }
        public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
            //	 Log.e("WEB","onGeolocationPermissionsShowPrompt url-===>"+origin);
            super.onGeolocationPermissionsShowPrompt(origin, callback);
            callback.invoke(origin, true, false);
        }
        @Override
        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
            loading_dialog.dismiss();
            new AlertDialog.Builder(currContext)
                    .setTitle("확인")
                    .setMessage(message)
                    .setPositiveButton("OK",
                            new AlertDialog.OnClickListener()
                            {
                                public void onClick(DialogInterface dialog, int which)
                                {
                                    result.confirm();
                                }
                            })
                    .setCancelable(false)
                    .create()
                    .show();
            return true;
        }
        public boolean onJsConfirm(WebView view, String url, String message,final JsResult result) {
            loading_dialog.dismiss();
            new AlertDialog.Builder(view.getContext())
                    .setTitle("확인")
                    .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;
        }


        @SuppressLint("SetJavaScriptEnabled")
        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg)
        {
            System.err.println("create new");
            WebView newWebView = new WebView(MainActivity.this);

            newWebView.setBackgroundColor(Color.GRAY);
            newWebView.getSettings().setJavaScriptEnabled(true);
            newWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
            newWebView.setWebChromeClient(new MyWebChromeClient());


            activity_main.addView(newWebView);
            isNewWeb = true;
            WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
            transport.setWebView(newWebView);
            resultMsg.sendToTarget();

            newWebView.setWebViewClient(new WebViewClient()
            {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url)
                {
                    view.loadUrl(url);
                    return false;
                }
            });
            return true;
        }

        @Override
        public void onCloseWindow(WebView window)
        {
            super.onCloseWindow(window);
            System.err.println("closing");
            activity_main.removeViewAt(activity_main.getChildCount() - 1);
        }
        /*

        @Override
        public void onCloseWindow(WebView window) {
            super.onCloseWindow(window);
            Log.e("WEB","window close");

            window.setVisibility(View.GONE);
            thisWebView.removeView(window);
        }
        */

        //For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg){
            mUM = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            MainActivity.this.startActivityForResult(Intent.createChooser(i,"File Chooser"), FCR);
        }
        // For Android 3.0+, above method not supported in some android 3+ versions, in such case we use this
        public void openFileChooser(ValueCallback uploadMsg, String acceptType){
            mUM = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            MainActivity.this.startActivityForResult(
                    Intent.createChooser(i, "File Browser"),
                    FCR);
        }
        //For Android 4.1+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
            mUM = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            MainActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), MainActivity.FCR);
        }
        //For Android 5.0+
        public boolean onShowFileChooser(
                WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams){
            if(mUMA != null){
                mUMA.onReceiveValue(null);
            }
            mUMA = filePathCallback;
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if(takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null){
                File photoFile = null;
                try{
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCM);
                }catch(IOException ex){
                    Log.e(TAG, "Image file creation failed", ex);
                }
                if(photoFile != null){
                    mCM = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                }else{
                    takePictureIntent = null;
                }
            }
            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("*/*");
            if(multiple_files) {
                contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            }
            Intent[] intentArray;
            if(takePictureIntent != null){
                intentArray = new Intent[]{takePictureIntent};
            }else{
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
            if(multiple_files && Build.VERSION.SDK_INT >= 18) {
                chooserIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            }
            startActivityForResult(chooserIntent, FCR);
            return true;
        }

    }
    // Create an image file
    private File createImageFile() throws IOException{
        @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "img_"+timeStamp+"_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        return File.createTempFile(imageFileName,".jpg",storageDir);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent){
        super.onActivityResult(requestCode, resultCode, intent);
        if(Build.VERSION.SDK_INT >= 21){
            Uri[] results = null;
            //Check if response is positive
            if(resultCode== Activity.RESULT_OK){
                if(requestCode == FCR){
                    if(null == mUMA){
                        return;
                    }
                    if(intent == null || intent.getData() == null){
                        //Capture Photo if no image available
                        if(mCM != null){
                            results = new Uri[]{Uri.parse(mCM)};
                        }
                    }else{
                        String dataString = intent.getDataString();
                        if(dataString != null){
                            results = new Uri[]{Uri.parse(dataString)};
                        } else {
                            if(multiple_files) {
                                if (intent.getClipData() != null) {
                                    final int numSelectedFiles = intent.getClipData().getItemCount();
                                    results = new Uri[numSelectedFiles];
                                    for (int i = 0; i < numSelectedFiles; i++) {
                                        results[i] = intent.getClipData().getItemAt(i).getUri();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            Log.d("activityRresult"," Result OK > results -"+results  );
            //  if(results != null){
            mUMA.onReceiveValue(results);
            mUMA = null;
            //  }
        }else{
            if(requestCode == FCR){
                if(null == mUM) return;
                Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();

                Log.d("activityRresult"," Result FAIL");

                //   if(result != null){
                mUM.onReceiveValue(result);
                mUM = null;

                // }
            }
        }
    }
    @Override
    public void onConfigurationChanged(Configuration newConfig){
        super.onConfigurationChanged(newConfig);
    }

    private boolean isNewWeb = false;

    private long backKeyPressedTime = 0;

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(isNewWeb && activity_main != null && activity_main.getChildCount()  > 0){
            activity_main.removeViewAt(activity_main.getChildCount() - 1);
            return true;
        }
        // 조건#1 back button 1l
        if ((keyCode == KeyEvent.KEYCODE_BACK) && System.currentTimeMillis() > backKeyPressedTime + 2000) {
            backKeyPressedTime = System.currentTimeMillis();

            //웹인지 아닌지를 선택해서 종료하 ㅁ
            if ((keyCode == KeyEvent.KEYCODE_BACK) && thisWebView.canGoBack()) {

                WebBackForwardList mWebBackForwardList = thisWebView.copyBackForwardList();

                String historyUrl = mWebBackForwardList.getItemAtIndex(mWebBackForwardList.getCurrentIndex() - 1).getUrl();
                Log.i("SHO", "historyUrl->" + historyUrl);
                if (historyUrl.equals("http://www.quantking.co.kr/lib/board_process.php")) {
                    thisWebView.goBackOrForward(-2);
                } else {
                    thisWebView.goBack();
                }

                return true;

            } else { //더이상 웹이 없으면 종료한

                new AlertDialog.Builder(this)
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .setTitle(R.string.app_name+ " 종료") // 제목부분 텍스트
                        .setMessage(R.string.app_name+"을  종료하시겠습니까?") // 내용부분 텍스트
                        .setPositiveButton(this.getString(android.R.string.yes), //승인버튼을 눌렀을때..
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        moveTaskToBack(true);
                                        // finish(); //종료
                                        finishApp();
                                    }
                                }
                        ).setNegativeButton(this.getString(android.R.string.no), null).show(); //취소버튼을 눌렀을때..
                return true;
            }

        } else if ((keyCode == KeyEvent.KEYCODE_BACK) && (System.currentTimeMillis() <= backKeyPressedTime + 2000)) { //조건 #2 back Button 2번 -> 종료

            new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setTitle(R.string.app_name+" 종료") // 제목부분 텍스트
                    .setMessage(R.string.app_name+"을 종료하시겠습니까?") // 내용부분 텍스트
                    .setPositiveButton(this.getString(android.R.string.yes), //승인버튼을 눌렀을때..
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    moveTaskToBack(true);
                                    // finish(); //종료
                                    finishApp();
                                }
                            }
                    ).setNegativeButton(this.getString(android.R.string.no), null).show(); //취소버튼을 눌렀을때..
        }

        return true;
    }

    /**
     * 앱 종료시 홈 버튼을 누른 효과를 낸다
     * 참고 : http://memesong.blogspot.kr/2011/07/blog-post_26.html
     */
    public void finishApp(){
        // String thisURL = URLConfig.INDEX_HTML + "?device_key=" + regid;

        //   thisWebView.loadUrl(thisURL);

        Intent intent = new Intent();
        intent.setAction("android.intent.action.MAIN");
        intent.addCategory("android.intent.category.HOME");
        intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
                | Intent.FLAG_ACTIVITY_FORWARD_RESULT
                | Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP
                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        startActivity(intent);
    }
    public class MyAsyncTask extends AsyncTask<Integer, Integer, Integer> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        @Override
        protected Integer doInBackground(Integer... integers){
            updatePushId();
            return 0;
        }
        @Override
        protected void onProgressUpdate(Integer... params) {
        }
        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);
        }
    }
    public void updatePushId(){
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        String phoneNum = "";
    /*   try{

     //       TelephonyManager telManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
      //      phoneNum = telManager.getLine1Number();
      //      if(phoneNum.startsWith("+82")){
      //          phoneNum = phoneNum.replace("+82", "0");
      //      }

        }catch(SecurityException e){
            e.printStackTrace();

        }
    */
        Log.d("firebase","updatePushId phone-"+phoneNum);
        Log.d("firebase","updatePushId Token-"+refreshedToken);


    }

}
