package com.raataar.zitate_love;

import android.app.ActionBar;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;

import com.raataar.zitate_love.adater.MainmenueListAdapter;
import com.raataar.zitate_love.app.AppController;
import com.raataar.zitate_love.model.Mainmenue;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;


public class MainActivity extends Activity {
    // Log tag
    private static final String TAG = MainActivity.class.getSimpleName();

    // Json url
    private static final String url = "http://api.raataar.de/sapientia-home";
    private ProgressDialog pDialog;
    private List<Mainmenue> mainmenueList = new ArrayList<Mainmenue>();
    private ListView listView;
    private MainmenueListAdapter adapter;

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


        //Prüfen ob Internet vorhanden
        if (isOnline()==false){
            pDialog = new ProgressDialog(MainActivity.this);
            // Showing progress dialog before making http request
            pDialog.setMessage("Keine Internetverbindung! \n\nDiese App benötigt eine funktionierende Internetverbindung.");
            pDialog.setCancelable(false);
            pDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Beenden", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    moveTaskToBack(true);
                    finish();
                    //return true;
                }
            });
            pDialog.show();
        }


        listView = (ListView) findViewById(R.id.list);
        adapter = new MainmenueListAdapter(this, mainmenueList);
        listView.setAdapter(adapter);

        // changing action bar color
        getActionBar().setBackgroundDrawable(
                new ColorDrawable(Color.parseColor("#1b1b1b")));


        ActionBar actionBar = getActionBar();
        //actionBar.setDisplayHomeAsUpEnabled(true);

        //Listbox füllen
        updateListView();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                //Toast.makeText(MainActivity.this, "You Clicked at " + mainmenueList.get(+position).getObjectId(), Toast.LENGTH_SHORT).show();
                startMenueActivity(mainmenueList.get(+position).getObjectActivity(), mainmenueList.get(+position).getObjectId(), mainmenueList.get(+position).getTitle());
            }
        });



    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }


    public void updateListView() {

        pDialog = new ProgressDialog(this);
        // Showing progress dialog before making http request
        pDialog.setMessage("Lade...");
        pDialog.show();


        // Creating volley request obj
        JsonArrayRequest menueReq = new JsonArrayRequest(url
                , new Response.Listener<JSONArray>() {

            @Override
            public void onResponse(JSONArray response) {
                Log.d(TAG, response.toString());
                hidePDialog();

                //Toast.makeText(MainActivity.this, String.valueOf(response.length()), Toast.LENGTH_SHORT).show();

                // Parsing json
                for (int i = 0; i < response.length(); i++) {
                    try {

                        JSONObject obj = response.getJSONObject(i);
                        Mainmenue mainmenue = new Mainmenue();
                        mainmenue.setTitle(obj.getString("title"));
                        mainmenue.setImage(obj.getString("image"));
                        mainmenue.setObjectId(obj.getString("objectId"));
                        mainmenue.setAnzahl(obj.getString("anzahl"));
                        mainmenue.setBeschreibung(obj.getString("beschreibung"));
                        mainmenue.setObjectActivity(obj.getString("objectActivity"));

                        // adding movie to movies array
                        mainmenueList.add(mainmenue);

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

                }

                // notifying list adapter about data changes
                // so that it renders the list view with updated data
                adapter.notifyDataSetChanged();
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();

            }


        });
        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(menueReq);
    }

    public void startMenueActivity(String MyClass, String objectID, String titel){

        try {
            Intent openNewIntent = new Intent( this, Class.forName( AppController.getInstance().getPackageURL() + MyClass ) );
            //Toast.makeText(MainActivity.this, "Starte Activity " + MyClass, Toast.LENGTH_SHORT).show();
            openNewIntent.putExtra("objectID",objectID);
            openNewIntent.putExtra("titel",titel);
            startActivity(openNewIntent );
        } catch (ClassNotFoundException e) {
            //Toast.makeText(MainActivity.this, "Nicht gefunden Activity " + MyClass, Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }

    }


    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    /** FIX sorgt dafür das Icons im Menu dargestellt werden **/

    @Override
    public boolean onMenuOpened(int featureId, Menu menu)
    {
        if(featureId == Window.FEATURE_ACTION_BAR && menu != null){
            if(menu.getClass().getSimpleName().equals("MenuBuilder")){
                try{
                    Method m = menu.getClass().getDeclaredMethod(
                            "setOptionalIconsVisible", Boolean.TYPE);
                    m.setAccessible(true);
                    m.invoke(menu, true);
                }
                catch(NoSuchMethodException e){
                    Log.e(TAG, "onMenuOpened", e);
                }
                catch(Exception e){
                    throw new RuntimeException(e);
                }
            }
        }
        return super.onMenuOpened(featureId, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.action_quit:
                moveTaskToBack(true);
                finish();
                return true;
            case R.id.action_refresh:
                mainmenueList.clear();
                updateListView();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public boolean isOnline() {

        Runtime runtime = Runtime.getRuntime();
        try {

            Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
            int     exitValue = ipProcess.waitFor();
            return (exitValue == 0);

        } catch (IOException e)          { e.printStackTrace(); }
        catch (InterruptedException e) { e.printStackTrace(); }

        return false;
    }

}
