package com.raataar.weisheiten_tvstar;

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.Window;
import android.widget.TextView;

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.weisheiten_tvstar.app.AppController;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Method;


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

    // Json url
    private String url = "http://api.raataar.de/sapientia-news/";
    private ProgressDialog pDialog;
    private String urlObjectId;
    private String customTitle;
    private String Anzahl;

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

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

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

        this.setTitle("News");
        if(bundlevalues!=null)
        {

            urlObjectId = (String) bundlevalues.get("objectID");
            customTitle=(String) bundlevalues.get("titel");
            this.setTitle("Weisheit: " + customTitle);

        }



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


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


        updateNews();



    }


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

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

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


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

                    JSONObject obj = response.getJSONObject(i);


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


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

                    TextView news_title = (TextView)findViewById(R.id.news_title);
                    TextView objectid = (TextView)findViewById(R.id.objectid);

                    TextView news_content = (TextView)findViewById(R.id.news_content);

                    news_image.setImageUrl(obj.getString("news_image"), imageLoader);
                    news_title.setText(obj.getString("news_title"));
                    objectid.setText(obj.getString("objectId"));
                    news_content.setText(obj.getString("news_content"));

                    urlObjectId=obj.getString("objectId");
                    Anzahl=obj.getString("anzahl");

                    //Toast.makeText(NewsActivity.this, obj.getString("lastId") + " xxx " + obj.getString("objectId"), Toast.LENGTH_SHORT).show();

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


    @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.news_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:
                updateNews();
                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);
        }
    }

}
