package com.dimchel.test.sportsclient;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class SiteActivity extends AppCompatActivity
{
    private WebView webView;

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

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        initComponents();

        Bundle extras = getIntent().getExtras();
        if (extras != null)
        {
            String title = extras.getString("title");
            String link = extras.getString("url");

            getSupportActionBar().setTitle(title);

            loadUrl(link);
        }

    }

    private void initComponents()
    {
        webView = (WebView) findViewById(R.id.webView);

        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        webView.setWebChromeClient(new WebChromeClient());

        // catching backButton on the wevView
        webView.setOnKeyListener(new View.OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    switch (keyCode) {
                        case KeyEvent.KEYCODE_BACK:
                            if (webView.canGoBack()) {
                                webView.goBack();
                                return true;
                            }
                            break;
                    }
                }

                return false;
            }
        });
    }

    public void loadUrl(String url)
    {
        if (url != null) {
            Log.v("gg", "load url: " + "http://" + url);
            webView.loadUrl("http://" + url);
        }
    }
}
