package com.raataar.sprueche_tvstarlite;

import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
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;
import com.raataar.sprueche_tvstarlite.adater.AutorenListAdapter;
import com.raataar.sprueche_tvstarlite.app.AppController;
import com.raataar.sprueche_tvstarlite.model.Autoren;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

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

    // Json url
    private String url = "http://api.raataar.de/sapientia-autoren/";
    private ProgressDialog pDialog;
    private List<Autoren> autorenList = new ArrayList<Autoren>();
    private ListView listView;
    private AutorenListAdapter adapter;
    private String urlObjectId;


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

        AdView mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder()
                .build();
        mAdView.loadAd(adRequest);

        Intent intent= getIntent();
        Bundle bundlevalues = intent.getExtras();

        if(bundlevalues!=null)
        {
            urlObjectId=(String) bundlevalues.get("objectID");
            //Textv.setText(j);
        }


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

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


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


        // URL anpassen
        url = url + AppController.getMD5(getApplicationInfo().loadLabel(getPackageManager()).toString());

        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(autorenList.get(+position).getObjectActivity(),autorenList.get(+position).getObjectId(),autorenList.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 Autoren...");
        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);
                        Autoren autorenmodel = new Autoren();
                        autorenmodel.setTitle(obj.getString("title"));
                        autorenmodel.setImage(obj.getString("image"));
                        autorenmodel.setObjectId(obj.getString("objectId"));
                        autorenmodel.setAnzahl(obj.getString("anzahl"));
                        autorenmodel.setBeschreibung(obj.getString("beschreibung"));
                        autorenmodel.setObjectActivity(obj.getString("objectActivity"));

                        // adding movie to movies array
                        autorenList.add(autorenmodel);

                    } 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;
        }
    }

    public void startSubMenueActivity(String MyClass){

        try {
            Intent openNewIntent = new Intent( this, Class.forName( AppController.getInstance().getPackageURL() + MyClass ) );
            startActivity(openNewIntent );
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.autor_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:
                autorenList.clear();
                updateListView();
                return true;
            case R.id.action_search:
                startSubMenueActivity("SuchenActivity");
                return true;
            case R.id.action_kategorie:
                startSubMenueActivity("KategorieActivity");
                return true;
            case R.id.action_autoren:
                startSubMenueActivity("AutorenActivity");
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

}
