package de.dhbw.vote;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import de.dhbw.navigation.R;

/**
 * Created by Mark on 29.09.2016.
 */
public class VoteFragment extends Fragment
{
    private Context mContext;
    private View mView;

    private WebView mWebView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        setHasOptionsMenu(true);

        mContext = getActivity();

        mView = inflater.inflate(R.layout.fragment_vote, container, false);

        mWebView = (WebView) mView.findViewById(R.id.vote_webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebViewClient(new VoteFragment.CustomWebViewClient());
        mWebView.loadUrl("https://minecraft-server.eu/vote/index/2421");

        return mView;
    }

    private class CustomWebViewClient extends WebViewClient
    {

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

            String voteName = PreferenceManager.getDefaultSharedPreferences(mContext).getString(getString(R.string.pref_vote_name_key),"");
            view.loadUrl("javascript:(function(){var id=setInterval(function(){if(document.getElementsByName('minecraftname').length>0){document.getElementsByName('minecraftname')[0].value='"+voteName+"';clearInterval(id);}},100);})()");
            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    }
}