package pl.helion.javaee7.klientogloszen;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class MainActivity extends ActionBarActivity {

    private DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pobierzWszystkie();
        final ListView listView = (ListView)findViewById(R.id.listView);
        final Activity self = this;
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                Ogloszenie o = (Ogloszenie)listView.getItemAtPosition(position);
                new AlertDialog.Builder(self)
                        .setTitle("Szczegóły rekordu")
                        .setMessage(o.toString())
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .show();
            }
        });
    }

    public void pobierzWszystkie() {
        new ZadanieHttpPobranieWszystkich().execute("GET", "http://10.3.1.7:8080/SerwerOgloszen/webresources/ogloszenie/");
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private List<Ogloszenie> konwertuj(String json) {
        List<Ogloszenie> wynik = new ArrayList<Ogloszenie>();
        try {
            JSONArray tablica = new JSONArray(json);
            for (int i = 0; i < tablica.length(); i++) {
                JSONObject o = tablica.getJSONObject(i);
                Ogloszenie ogloszenie = new Ogloszenie();
                ogloszenie.setId(o.getInt("id"));
                ogloszenie.setAutor(o.getString("autor"));
                ogloszenie.setTytul(o.getString("tytul"));
                ogloszenie.setTresc(o.getString("tresc"));
                Date data = df.parse(o.getString("dataPublikacji"));
                ogloszenie.setDataPublikacji(data);
                wynik.add(ogloszenie);

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return wynik;
    }

    public void odswiez(String wynik) {
        //Toast.makeText(getBaseContext(), wynik, Toast.LENGTH_LONG).show();
        List<Ogloszenie> lista = this.konwertuj(wynik);
        ListView listView = (ListView)findViewById(R.id.listView);
        listView.setAdapter(new AdapterOgloszen(this, lista));
    }


    public void aktywnoscDodaj(View view) {
        Intent intent = new Intent(this, AddNewActivity.class);
        startActivity(intent);
    }

    class ZadanieHttpPobranieWszystkich extends ZadanieHttp {
        @Override
        protected void onPostExecute(String wynik) {
            odswiez(wynik);
        }
    }

    class AdapterOgloszen extends ArrayAdapter<Ogloszenie> {
        public AdapterOgloszen(Context context, List<Ogloszenie> ogloszenia) {
            super(context, 0, ogloszenia);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Ogloszenie ogloszenie = getItem(position);
            if (convertView == null)
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.element_listy, parent, false);
            TextView txtTytul = (TextView) convertView.findViewById(R.id.txtTytul);
            TextView txtTresc = (TextView) convertView.findViewById(R.id.txtTresc);
            txtTytul.setText(ogloszenie.getTytul());
            txtTresc.setText(ogloszenie.getTresc());
            return convertView;
        }
    }
}
