package smart_gs.network;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import jp.ac.nii.hcp.client.net.UnauthorizedException;
import jp.ac.nii.hcp.client.shared.HCPClientException;
import jp.ac.nii.hcp.shared.model.HCPUserGroup;
import smart_gs.debugprint.Debugprint;
import smart_gs.swingui.ButtonFrame;

public class SelectGroupFrame extends ButtonFrame implements ListSelectionListener, ActionListener {

	private JList list;
	private List<HCPUserGroup> groups;

	public SelectGroupFrame(String action) {
		super("Select Group");
		ProjectHandler.getInstance().setAction(action);
		this.list = new JList();
		try {
			this.makeList();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			new ShowResultDialog("Select Group", e).setVisible(true);
		} catch (UnauthorizedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			new ShowResultDialog("Select Group", e).setVisible(true);
		}
		
		JPanel panel = (JPanel) this.getContentPane();
		this.setSize(new Dimension(350,300));
		this.setMaximumSize(new Dimension(350,1000));
		list.addListSelectionListener(this);
		list.setVisibleRowCount(20);
		JScrollPane sPane = new JScrollPane(list);
	    panel.add(sPane,BorderLayout.NORTH);


	}

	private void makeList() throws IOException, UnauthorizedException {
		ProjectHandler handler = ProjectHandler.getInstance();
		if (handler.authenticated()) {
			this.groups = handler.getGroups(handler.getAuthenticationCache());
			DefaultListModel model = new DefaultListModel();
			for (int i = 0; i < groups.size(); i++) {
				model.addElement(groups.get(i).name);
			}
			this.list.setModel(model);
		} else {
			handler.authenticate();
		}
	}

	@Override
	public void valueChanged(ListSelectionEvent arg0) {
	}

	@Override
	public void ok() {
		String id = this.getSelectedGroup().id;
		Debugprint.from();
		Debugprint.message("Selected Group ID: " + id);
		ProjectHandler.getInstance().setGroup(this.getSelectedGroup());
		ProjectHandler.getInstance().perform();
		this.dispose();		
	}

	private HCPUserGroup getSelectedGroup() {
		int index = this.list.getSelectedIndex();
		return this.groups.get(index);
	}

	@Override
	public void cancel() {
		this.dispose();
	}
}
