package com.xikka.client;

import java.awt.Dimension;
import java.util.function.Function;

import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;

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

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.exceptions.UnirestException;

class GamesPanel extends JPanel implements SelectablePanel {
	private static final long serialVersionUID = 7993365654825410556L;
	
	private final JList<String> gameList;
	private final DefaultListModel<String> gameListModel;

	GamesPanel(Function<String, Void> onSelectGame) {
		setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
		
		gameListModel = new DefaultListModel<String>();
		gameList = new JList<String>(gameListModel);
		gameList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		gameList.setPreferredSize(new Dimension(100, 200));
		add(gameList);
		
		JButton ok = new JButton();
		ok.setText("Select game");
		ok.addActionListener(a -> {
			onSelectGame.apply(gameList.getSelectedValue());
		});
		add(ok);
	}
	
	public void onSelect() {
		gameListModel.removeAllElements();
		// Get list of games
		try {
			HttpResponse<JsonNode> resp = GameClientMain
					.get("games")
					.asJson();
			System.out.println("Games response: " + resp.getBody());
			JSONArray a = resp.getBody().getArray();
			for (int i = 0; i < a.length(); i++) {
				JSONObject o = a.getJSONObject(i);
				gameListModel.addElement(o.getString("name"));
			}
		} catch (UnirestException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		gameList.setSelectedIndex(0);
	}
}
