package com.puntoz.pro;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {

    WebView webView;
    String PANEL_URL = "http://216.152.155.250/PUNTOZ_PANEL/preview.php?apk_tv=1";

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

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        webView = new WebView(this);
        setContentView(webView);

        webView.setFocusable(true);
        webView.setFocusableInTouchMode(true);
        webView.requestFocus();

        WebSettings s = webView.getSettings();
        s.setJavaScriptEnabled(true);
        s.setDomStorageEnabled(true);
        s.setMediaPlaybackRequiresUserGesture(false);
        s.setLoadWithOverviewMode(true);
        s.setUseWideViewPort(true);
        s.setTextZoom(100);
        s.setSupportZoom(false);
        s.setBuiltInZoomControls(false);
        s.setDisplayZoomControls(false);
        s.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

        webView.setWebChromeClient(new WebChromeClient());
        webView.addJavascriptInterface(new AndroidBridge(), "PuntozAndroid");

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                aplicarModoTV();
            }
        });

        webView.loadUrl(PANEL_URL);
    }

    public class AndroidBridge {
        @JavascriptInterface
        public void openPlayer(String url) {
            if (url == null || url.trim().isEmpty()) return;

            Intent i = new Intent(MainActivity.this, PlayerActivity.class);
            i.putExtra("url", url);
            startActivity(i);
        }
    }

    private void aplicarModoTV() {
        String js =
        "javascript:(function(){"
        + "var meta=document.querySelector('meta[name=viewport]');"
        + "if(!meta){meta=document.createElement('meta');meta.name='viewport';document.head.appendChild(meta);}"
        + "meta.content='width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no';"
        + "document.documentElement.style.margin='0';"
        + "document.documentElement.style.padding='0';"
        + "document.body.style.margin='0';"
        + "document.body.style.padding='0';"
        + "document.body.style.overflow='hidden';"
        + "document.body.style.width='100vw';"
        + "document.body.style.height='100vh';"

        + "var root=document.body;"
        + "root.style.transformOrigin='top left';"
        + "function fixScale(){"
        + "var sw=window.innerWidth/1920;"
        + "var sh=window.innerHeight/1080;"
        + "var sc=Math.min(sw,sh);"
        + "root.style.width='1920px';"
        + "root.style.height='1080px';"
        + "root.style.transform='scale('+sc+')';"
        + "}"
        + "fixScale();window.onresize=fixScale;"

        + "window.pzItems=function(){return Array.from(document.querySelectorAll('a,button,[onclick],[data-url],[data-stream],[data-src],.channel,.canal,.card,.item,.poster')).filter(function(e){var r=e.getBoundingClientRect();return r.width>20&&r.height>20;});};"
        + "var items=window.pzItems();"
        + "items.forEach(function(e){e.setAttribute('tabindex','0');e.style.outline='none';});"
        + "var st=document.createElement('style');"
        + "st.innerHTML='*:focus{outline:5px solid #ffffff!important;outline-offset:4px!important;transform:scale(1.04);z-index:9999!important;}';"
        + "document.head.appendChild(st);"
        + "if(items.length>0){items[0].focus();}"

        + "document.addEventListener('click',function(ev){"
        + "var e=ev.target.closest('a,button,[onclick],[data-url],[data-stream],[data-src],.channel,.canal,.card,.item,.poster');"
        + "if(!e)return;"
        + "var u=e.getAttribute('data-url')||e.getAttribute('data-stream')||e.getAttribute('data-src')||e.href||'';"
        + "if(u.indexOf('.m3u8')>-1||u.indexOf('.mp4')>-1||u.indexOf('.mkv')>-1||u.indexOf('stream')>-1||u.indexOf('player')>-1){ev.preventDefault();PuntozAndroid.openPlayer(u);}"
        + "},true);"

        + "window.pzMove=function(dir){"
        + "var all=window.pzItems();var cur=document.activeElement;var i=all.indexOf(cur);"
        + "if(i<0)i=0;"
        + "if(dir=='down'&&all[i+1])all[i+1].focus();"
        + "if(dir=='up'&&all[i-1])all[i-1].focus();"
        + "if(dir=='right'&&all[i+1])all[i+1].focus();"
        + "if(dir=='left'&&all[i-1])all[i-1].focus();"
        + "};"
        + "})();";

        webView.evaluateJavascript(js, null);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            int k = event.getKeyCode();

            if (k == KeyEvent.KEYCODE_DPAD_CENTER || k == KeyEvent.KEYCODE_ENTER) {
                webView.evaluateJavascript("document.activeElement&&document.activeElement.click();", null);
                return true;
            }

            if (k == KeyEvent.KEYCODE_DPAD_DOWN) { webView.evaluateJavascript("window.pzMove&&window.pzMove('down');", null); return true; }
            if (k == KeyEvent.KEYCODE_DPAD_UP) { webView.evaluateJavascript("window.pzMove&&window.pzMove('up');", null); return true; }
            if (k == KeyEvent.KEYCODE_DPAD_RIGHT) { webView.evaluateJavascript("window.pzMove&&window.pzMove('right');", null); return true; }
            if (k == KeyEvent.KEYCODE_DPAD_LEFT) { webView.evaluateJavascript("window.pzMove&&window.pzMove('left');", null); return true; }
        }

        return super.dispatchKeyEvent(event);
    }
}
