package com.raataar.sprueche_love;

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.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import android.view.Window;
import android.widget.*;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.raataar.sprueche_love.app.AppController;
import com.raataar.sprueche_love.util.RoundedTransformation;
import com.squareup.picasso.Picasso;

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

import java.lang.reflect.Method;


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

    // Json url
    private String url = "http://api.raataar.de/sapientia-zitat/";
    private ProgressDialog pDialog;
    private String urlObjectId;
    private String customTitle;
    private String zitatsharetext;
    private String HTMLImageLink;
    private String HTMLAutorLink;


    //Intent für den Sharbutton
    private Intent shareIntent;

    //ShareButtonProvider
    private ShareActionProvider mShareActionProvider;

    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

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

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

        shareIntent = new Intent(android.content.Intent.ACTION_SEND);
        shareIntent.setType("text/plain");

        this.setTitle("Zitat");
        if(bundlevalues!=null)
        {
            if(urlObjectId=="menue_zufall" || urlObjectId==null) {
                urlObjectId = (String) bundlevalues.get("objectID");
            }
            customTitle=(String) bundlevalues.get("titel");
            this.setTitle("Weisheit: " + customTitle);
            //Textv.setText(j);
        }

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


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

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


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

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

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


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

                        JSONObject obj = response.getJSONObject(i);


                        if (imageLoader == null)
                            imageLoader = AppController.getInstance().getImageLoader();


                        NetworkImageView kategorie_image = (NetworkImageView)findViewById(R.id.kategorie_image);


                        ImageView autoren_imagepic = (ImageView)findViewById(R.id.autoren_imagepic);


                        TextView zitat = (TextView)findViewById(R.id.zitat);
                        TextView objectid = (TextView)findViewById(R.id.objectid);
                        TextView autoren_id = (TextView)findViewById(R.id.autoren_id);
                        TextView kategorie_id = (TextView)findViewById(R.id.kategorie_id);


                        TextView kategorie_text = (TextView)findViewById(R.id.kategorie_text);
                        TextView kategorie_beschreibung = (TextView)findViewById(R.id.kategorie_beschreibung);
                        TextView autoren_text = (TextView)findViewById(R.id.autoren_text);
                        TextView autoren_beschreibung = (TextView)findViewById(R.id.autoren_beschreibung);
                        TextView autoren_imagequelle = (TextView)findViewById(R.id.autoren_imagequelle);
                        TextView autoren_moreinfo = (TextView)findViewById(R.id.autoren_moreinfo);

                        LinearLayout autoren_infoview= (LinearLayout)findViewById(R.id.autoren_infoview);

                        kategorie_image.setImageUrl(obj.getString("kategorie_image"), imageLoader);

                        Picasso.with(getApplicationContext())
                                .load(obj.getString("autor_image"))
                                .transform(new RoundedTransformation(8, 0))
                                .fit()
                                .into(autoren_imagepic);


                        // Zitat
                        zitat.setText(obj.getString("zitat"));

                        //Zitat für SHARE-Button
                        zitatsharetext=obj.getString("zitat");
                        zitatsharetext=zitatsharetext + " Von " + obj.getString("autoren_text");

                        //ShareButton Content übergeben
                        shareIntent.putExtra(Intent.EXTRA_SUBJECT, "");
                        shareIntent.putExtra(Intent.EXTRA_TEXT, zitatsharetext);

                        autoren_text.setText("Autor: " + obj.getString("autoren_text"));
                        kategorie_text.setText("Kategorie: " + obj.getString("kategorie_text"));

                        // objectid
                        objectid.setText(obj.getString("objectId"));

                        autoren_id.setText(obj.getString("autor_id"));
                        kategorie_id.setText(obj.getString("kategorie_id"));

                        autoren_beschreibung.setText(obj.getString("autoren_beschreibung"));
                        kategorie_beschreibung.setText(obj.getString("kategorie_beschreibung"));

                        HTMLImageLink=obj.getString("autoren_imagequelle");
                        HTMLAutorLink=obj.getString("autoren_wikilink");

                        autoren_imagequelle.setText(Html.fromHtml(HTMLImageLink));
                        autoren_imagequelle.setMovementMethod(LinkMovementMethod.getInstance());
                        autoren_moreinfo.setText(Html.fromHtml(HTMLAutorLink));
                        autoren_moreinfo.setMovementMethod(LinkMovementMethod.getInstance());

                        if (HTMLAutorLink.length()<3){

                            autoren_infoview.setVisibility(View.GONE);
                            //autoren_infoview

                        }

                        urlObjectId=obj.getString("objectId");

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

                }

            }
        }, 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 showImage(View v)
    {

    }




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

    public void startMenueActivity(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;
        }
    }


    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.zitat_menu, menu);

        /** Share-Button inalisieren */
        mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.menu_item_share).getActionProvider();
        mShareActionProvider.setShareIntent(shareIntent);
        mShareActionProvider.onCreateActionView();
        /** Sharebutton-Ini-ende **/

        return super.onCreateOptionsMenu(menu);
    }

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


}
