package smart_gs.network;

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

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import jp.ac.nii.hcp.client.net.AuthenticationCache;
import jp.ac.nii.hcp.shared.model.HCPProject;
import smart_gs.logical.Preference;
import smart_gs.swingui.ButtonFrame;

public class AuthFrame extends ButtonFrame implements ActionListener {

	private ProjectHandler handler;
	private JPanel settingPanel;
	private JPanel userNamePanel;
	private JTextField userNameField;

	private JPanel passPanel;
	private JPasswordField  passField;

	public AuthFrame(String title, ProjectHandler handler) {
		super(handler.getAction() + ": " + title);
		this.handler = handler;
		this.setResizable(true);
		this.setModalExclusionType(null);
//		this.setLocationRelativeTo(null);
		
		this.userNamePanel = new JPanel(new FlowLayout());
		this.userNamePanel.setBorder(new TitledBorder("ID"));
		this.userNameField = new JTextField(22);
		this.userNameField.setText(Preference.getInstance().getUserName());
		this.userNamePanel.add(userNameField);

		this.passPanel = new JPanel(new FlowLayout());
		this.passPanel.setBorder(new TitledBorder("Password"));
		this.passField = new JPasswordField(22);
		this.passField.setText("");
		this.passPanel.add(passField);

		this.settingPanel = new JPanel(new GridLayout(2, 1));
		this.settingPanel.add(this.userNamePanel);
		this.settingPanel.add(this.passPanel);
		
		this.getContentPane().add(this.settingPanel, BorderLayout.CENTER);
		this.setSize(new Dimension(400, 300));
		this.pack();
		
		this.getRootPane().setDefaultButton(this.okButton);
	}

	@Override
	public void ok() {
		String id = this.userNameField.getText();
		String pass = new String(this.passField.getPassword());
		this.passField.setText("");
		try {
			AuthenticationCache authCache = this.handler.makeAuthenticationCache(id,pass);
			if (authCache == null) {
				JOptionPane.showMessageDialog(this, "Authentication failed.");
				return;
			}
			this.handler.setAuthenticationCache(authCache);
			List<HCPProject> projects = this.handler.getProjectsFromRepository();
			ProjectExplorer.getInstance().addProjectList(projects, Constants.REPOSITORY);
			JOptionPane.showMessageDialog(this, "Authentication succeeded.");
			if (this.handler.getAction() != ProjectAction.AUTHENTICATE) {
				this.handler.perform();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			new ShowResultDialog("Authenticate", e).setVisible(true);
		}
		this.dispose();
	}


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

}
