package org.stepic.droid.ui.custom;

import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;

import org.stepic.droid.base.App;
import org.stepic.droid.configuration.Config;
import org.stepic.droid.ui.util.AssetSupportWebViewClient;
import org.stepic.droid.util.HtmlHelper;

import java.util.Calendar;

import javax.inject.Inject;

public class LatexSupportableWebView extends WebView implements View.OnClickListener, View.OnTouchListener {
    private static final String mimeType = "text/html";
    private static final String encoding = "UTF-8";

    private static final int MAX_CLICK_DURATION = 200;
    private long startClickTime;
    OnWebViewImageClicked listener;

    @Inject
    Config config;

    private final static String assetUrl = "file:///android_asset/";

    public LatexSupportableWebView(Context context) {
        this(context, null);
    }

    public LatexSupportableWebView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LatexSupportableWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        App.Companion.component().inject(this);
        setBackgroundColor(Color.TRANSPARENT);
        setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });

        setOnClickListener(this);
        setOnTouchListener(this);
    }


    public void setText(CharSequence text) {
        setText(text, false); //by default we do not want latex -> try to optimize
    }

    public void setText(CharSequence text, boolean wantLaTeX) {
        setText(text, wantLaTeX, null);
    }

    public void setText(CharSequence text, boolean wantLaTeX, String fontPath) {

        DisplayMetrics displaymetrics = new DisplayMetrics();
        ((AppCompatActivity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int width = displaymetrics.widthPixels;


        getSettings().setDomStorageEnabled(true);
        String textString = text.toString();

        final String html;
        WebSettings webSettings = getSettings();
        if (fontPath != null) {
            webSettings.setJavaScriptEnabled(true);
            html = HtmlHelper.buildPageWithCustomFont(text, fontPath, width, config.getBaseUrl());
        } else if (wantLaTeX || HtmlHelper.hasLaTeX(textString)) {
            webSettings.setJavaScriptEnabled(true);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                setWebViewClient(new AssetSupportWebViewClient());
            }
            html = HtmlHelper.buildMathPage(text, width, config.getBaseUrl());
        } else {
            html = HtmlHelper.buildPageWithAdjustingTextAndImage(text, width, config.getBaseUrl());
        }

        postDelayed(new Runnable() {
            @Override
            public void run() {
                loadDataWithBaseURL(assetUrl, html, mimeType, encoding, "");
            }
        }, 0);
    }


    @Override
    public void onClick(View v) {
        WebView.HitTestResult hr = getHitTestResult();
        try {
            if (listener != null && hr.getType() == HitTestResult.IMAGE_TYPE) {
                listener.onClick(hr.getExtra());
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                startClickTime = Calendar.getInstance().getTimeInMillis();
                break;
            }
            case MotionEvent.ACTION_UP: {
                long clickDuration = Calendar.getInstance().getTimeInMillis() - startClickTime;
                if (clickDuration < MAX_CLICK_DURATION) {
                    performClick();
                }
            }
        }
        return false;
    }


    float startX = 0;
    float startY = 0;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            startX = event.getX();
            startY = event.getY();
        } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
            float dx = startX - event.getX();
            float dy = startY - event.getY();
            event.setLocation(event.getX(), startY);

            if (Math.abs(dx) > Math.abs(dy) && canScrollHorizontally((int) dx)) {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
        } else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
            getParent().requestDisallowInterceptTouchEvent(false);
        }
        return super.onTouchEvent(event);
    }

    public void setOnWebViewClickListener(OnWebViewImageClicked listener) {
        this.listener = listener;
    }

    interface OnWebViewImageClicked {
        void onClick(String path);
    }
}

@@ -4291,24 +4291,32 @@
     %7D%0A%0A%0A    
+private 
 float startX
@@ -4321,24 +4321,32 @@
 tX = 0;%0A    
+private 
 float startY
@@ -4427,18 +4427,22 @@
         
-if
+switch
  (event.
@@ -4444,35 +4444,52 @@
 vent.getAction()
- ==
+) %7B%0A            case
  MotionEvent.ACT
@@ -4496,20 +4496,22 @@
 ION_DOWN
-) %7B%0A
+:%0A    
         
@@ -4545,24 +4545,28 @@
             
+    
 startY = eve
@@ -4588,39 +4588,35 @@
     
-%7D else if (event.getAction() ==
+    break;%0A            case
  Mot
@@ -4635,20 +4635,22 @@
 ION_MOVE
-) %7B%0A
+:%0A    
         
@@ -4679,32 +4679,36 @@
 - event.getX();%0A
+    
             floa
@@ -4749,16 +4749,20 @@
         
+    
 event.se
@@ -4803,24 +4803,28 @@
             
+   
+ 
 if (Math.abs
@@ -4889,32 +4889,36 @@
                 
+    
 getParent().requ
@@ -4959,32 +4959,36 @@
 e);%0A            
+  
+  
 %7D%0A        %7D else
@@ -4985,85 +4985,75 @@
     
-%7D else if (event.getAction() == MotionEvent.ACTION_UP %7C%7C event.getAction() ==
+    break;%0A            case MotionEvent.ACTION_UP:%0A            case
  Mot
@@ -5074,20 +5074,22 @@
 N_CANCEL
-) %7B%0A
+:%0A    
         
@@ -5143,24 +5143,43 @@
 ent(false);%0A
+            break;%0A
         %7D%0A  

clean up