package com.raataar.sapientia_hollywood;

import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
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.sapientia_hollywood.adater.SuchenByIDListAdapter;
import com.raataar.sapientia_hollywood.app.AppController;
import com.raataar.sapientia_hollywood.model.SuchenByID;
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;

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

    // Json url
    private String url = "http://api.raataar.de/sapientia-zitat-suche/";
    private ProgressDialog pDialog;
    private List<SuchenByID> suchenbyidList = new ArrayList<SuchenByID>();
    private ListView listView;
    private SuchenByIDListAdapter adapter;
    private String urlObjectId;
    private String customTitle;


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

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

        this.setTitle("Suchen");
        if(bundlevalues!=null)
        {
            urlObjectId=(String) bundlevalues.get("objectID");
            customTitle=(String) bundlevalues.get("searchtext");

            String searchText;
            searchText=customTitle;
            searchText=searchText.replaceAll("#ae#","ä");
            searchText=searchText.replaceAll("#Ae#","Ä");
            searchText=searchText.replaceAll("#ue#","ü");
            searchText=searchText.replaceAll("#Ue#","Ü");
            searchText=searchText.replaceAll("#Oe#","Ö");
            searchText=searchText.replaceAll("#oe#","ö");
            searchText=searchText.replaceAll("#ss#","ß");



            this.setTitle("Suchen nach - " + searchText);
            //Textv.setText(j);
        }


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

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


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

        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();
                String mysubstring;
                if (suchenbyidList.get(+position).getZitat().length()>25){
                    mysubstring=suchenbyidList.get(+position).getZitat().substring(0,25) + "...";
                }
                else{
                    mysubstring=suchenbyidList.get(+position).getZitat();
                }

                startMenueActivity(suchenbyidList.get(+position).getObjectActivity(),suchenbyidList.get(+position).getObjectId(),mysubstring);
            }
        });

    }

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


    public void updateListView() {

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


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

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

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

                //Toast.makeText(KategorieByIDActivity.this, urlObjectId, Toast.LENGTH_SHORT).show();
                //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);
                        SuchenByID suchenbyidlist = new SuchenByID();
                        suchenbyidlist.setZitat(obj.getString("zitat"));
                        suchenbyidlist.setImage(obj.getString("image"));
                        suchenbyidlist.setObjectId(obj.getString("objectId"));
                        suchenbyidlist.setAutoren_text(obj.getString("autoren_text"));
                        suchenbyidlist.setKategorie_text(obj.getString("kategorie_text"));
                        suchenbyidlist.setAutor_id(obj.getString("autor_id"));
                        suchenbyidlist.setKategorie_id(obj.getString("kategorie_id"));
                        suchenbyidlist.setObjectActivity(obj.getString("objectActivity"));

                        // adding movie to movies array
                        suchenbyidList.add(suchenbyidlist);

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

                }

                /** Keine Ergebnisse **/
                if ( response.length()==0){

                    pDialog = new ProgressDialog(SuchenByIDActivity.this);
                    // Showing progress dialog before making http request
                    pDialog.setMessage("Leider keine Treffer gefunden.");
                    pDialog.setCancelable(false);
                    pDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Zurück", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            dialog.dismiss();
                            finish();
                        }
                    });
                    pDialog.show();


                }

                // 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();
        }

    }

    public void startSubMenueActivity(String MyClass){

        try {
            Intent openNewIntent = new Intent( this, Class.forName( AppController.getInstance().getPackageURL() + MyClass ) );
            startActivity(openNewIntent );
        } catch (ClassNotFoundException e) {
            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.search_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_kategorie:
                startSubMenueActivity("KategorieActivity");
                return true;
            case R.id.action_autoren:
                startSubMenueActivity("AutorenActivity");
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

}
