package com.goadrich.mark.listviewdemo;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

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

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private ArrayList<AcronymItem> results;
    private CustomListAdapter myadapt;
    private Button button;
    private EditText et;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        

        button = (Button)findViewById(R.id.button);
        et = (EditText)findViewById(R.id.editText);

        ArrayList<AcronymItem> image_details = getListData();
        final ListView lv1 = (ListView) findViewById(R.id.listView);
        myadapt = new CustomListAdapter(this, image_details);
        lv1.setAdapter(myadapt);
        lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> a, View v, int position, long id) {
                Object o = lv1.getItemAtPosition(position);
                AcronymItem newsData = (AcronymItem) o;
                Toast.makeText(MainActivity.this, "Selected :" + " " + newsData, Toast.LENGTH_LONG).show();
            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    String encoded = URLEncoder.encode(et.getText().toString(), "UTF-8");
                    String searchURL = "http://www.nactem.ac.uk/software/acromine/dictionary.py?sf=" + encoded;
                    new GetAcs().execute(searchURL);
                } catch (UnsupportedEncodingException e) {
                    Log.d("Setup", "something went wrong");
                    e.printStackTrace();
                }

            }
        });

    }

    private ArrayList<AcronymItem> getListData() {
        results = new ArrayList<AcronymItem>();
        AcronymItem acronymItem = new AcronymItem();
        acronymItem.setDefinition("Sample Definition");
        acronymItem.setFrequency("374");
        acronymItem.setDate("Since 2005");
        results.add(acronymItem);

        // Add some more dummy data for testing
        return results;
    }

    private class GetAcs extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... acsUrl) {
            Log.d("Async", "Calling the do in background");

            StringBuilder acsBuilder = new StringBuilder();
            for (String searchURL : acsUrl) {

                HttpURLConnection urlConnection = null;
                try {
                    URL url = new URL(searchURL);
                    urlConnection = (HttpURLConnection) url.openConnection();

                    InputStream acsContent = urlConnection.getInputStream();
                    InputStreamReader acsInput = new InputStreamReader(acsContent);
                    BufferedReader acsReader = new BufferedReader(acsInput);
                    String lineIn;
                    while ((lineIn = acsReader.readLine()) != null) {
                        acsBuilder.append(lineIn);
                    }
                    Log.d("Async", "Got the result");

                } catch (Exception e) {
                    Log.d("Async", "What happened here??");
                    e.printStackTrace();
                } finally {
                    urlConnection.disconnect();
                }
            }
            return acsBuilder.toString();
        }

        protected void onPostExecute(String result) {
            try {
                results.clear();
                JSONArray resultObject = new JSONArray(result);
                JSONObject first = resultObject.getJSONObject(0);
                JSONArray inner = first.getJSONArray("lfs");
                Log.d("POSTEXECUTE", "found " + inner.length() + "results");
                for (int i = 0; i < inner.length(); i++) {
                    AcronymItem acronym = new AcronymItem();
                    acronym.setDefinition((String) inner.getJSONObject(i).get("lf"));
                    acronym.setFrequency("Frequency: " + (Integer) inner.getJSONObject(i).get("freq"));
                    acronym.setDate("Since " + (Integer) inner.getJSONObject(i).get("since"));

                    results.add(acronym);
                }

            } catch (Exception e) {
                Log.d("AsyncPost", "What happened here??");
                e.printStackTrace();
            } finally {
                myadapt.notifyDataSetChanged();
            }
        }
    }

}
