/*
 * @author Javier Martin Manzano
 */

package ub.incendishab;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;


public class Configuration extends AppCompatActivity {

    private Activity thisActivity;
    private HashMap map;
    private Bot bot;

    private SharedPreferences preferences;

    private AdapterView.OnItemSelectedListener changeChatIdListener = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String chat = parent.getItemAtPosition(position).toString();
            String chatId = map.get(chat).toString();
            bot.setChatId(chat);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString("chatId",chatId);
            editor.commit();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    };

    private View.OnClickListener returnListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            thisActivity.finish();


        }
    };

    private View.OnClickListener refreshListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setChatEntries();
            Spinner spinner = thisActivity.findViewById(R.id.chatSpinner);
            ArrayList<String> entries = new ArrayList<>();
            Iterator it = map.keySet().iterator();
            while (it.hasNext()) {
                entries.add((String)it.next());
            }
            ArrayAdapter<String> adapter = new ArrayAdapter<>(thisActivity, R.layout.support_simple_spinner_dropdown_item, entries);
            adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
            spinner.setAdapter(adapter);
            String chat = preferences.getString("chatId","-391609739");
            int i = 0;
            boolean found = false;
            while (i<entries.size() && !found){
                if (entries.get(i).equals(chat)) {
                    spinner.setSelection(i);
                    found = true;
                }
                i++;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        thisActivity = this;
        preferences = getSharedPreferences("Prefs", Context.MODE_PRIVATE);
        map = new HashMap();
        bot = Bot.getBot();
        setContentView(R.layout.activity_config);
        setChatEntries();
        Button button = findViewById(R.id.returnButton);
        button.setOnClickListener(returnListener);
        Button button2 = findViewById(R.id.refreshButton);
        button2.setOnClickListener(refreshListener);
        Spinner spinner = thisActivity.findViewById(R.id.chatSpinner);
        spinner.setOnItemSelectedListener(changeChatIdListener);
    }

    private void setChatEntries(){
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                String url = "https://api.telegram.org/bot675006415:AAH0aANGFlcB1l88yDMv1VJnBSgX8W1k9FU/getUpdates";
                JSONObject res = null;
                try {
                    URL obj = new URL(url);
                    HttpURLConnection con = (HttpURLConnection)obj.openConnection();
                    con.setRequestMethod("GET");
                    con.setRequestProperty("User-Agent", "Mozilla/5.0");
                    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    String inputLine;
                    StringBuffer response = new StringBuffer();

                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();
                    res = new JSONObject(response.toString());
                    try {
                        JSONObject chat;
                        String id, title;
                        for (int i=0;i<((JSONArray)res.get("result")).length();i++) {
                            chat = (JSONObject)((JSONObject)((JSONObject)((JSONArray)res.get("result")).get(i)).get("message")).get("chat");
                            id = chat.get("id").toString();
                            title = chat.get("title").toString();
                            map.put(title,id);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    Toast.makeText(thisActivity, "Fallo de conexión. ¿Hay acceso a Internet?",Toast.LENGTH_LONG).show();

                }
            }
        });
        thread.start();
    }
}
