package com.xikka.client;

import java.util.function.BiFunction;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import org.json.JSONObject;

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

class LoginPanel extends JPanel {
	private static final long serialVersionUID = -7073075288582991784L;
	
	LoginPanel(BiFunction<Integer, String, Void> onLogin) {
		setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
		// Server selection dialog
		JTextField email = new JTextField("testing1@example.com");
		JPasswordField pass = new JPasswordField("test");
		add(email);
		add(pass);
		
		JButton ok = new JButton();
		ok.setText("Login");
		ok.addActionListener(e -> {
			try {
				JSONObject loginRequest = new JSONObject();
				loginRequest.put("credentialType", "password");
				loginRequest.put("email", email.getText());
				loginRequest.put("password", new String(pass.getPassword()));
				HttpResponse<JsonNode> resp = GameClientMain
					.post("accounts/login")
					.header("content-type", "application/json")
					.body(loginRequest)
					.asJson();
				GameClientMain.handleErrorResponses(resp);
				int status = resp.getStatus();
				System.out.println(resp.getBody());
				if (status == 200) {
					JSONObject o = resp.getBody().getObject();
					int userId = o.getJSONObject("user").getInt("userId");
					String token = o.getString("token");
					onLogin.apply(userId, token);
				}
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		});
		
		add(ok);
		
		JTextField runame = new JTextField("Username");
		JTextField remail = new JTextField("Email");
		JPasswordField rpass = new JPasswordField("Password");
		add(runame);
		add(remail);
		add(rpass);
		
		JButton reg = new JButton();
		reg.setText("Register");
		reg.addActionListener(e -> {
			try {
				JSONObject registerRequest = new JSONObject();
				registerRequest.put("username", runame.getText());
				registerRequest.put("email", remail.getText());
				registerRequest.put("password", new String(rpass.getPassword()));
				HttpResponse<JsonNode> resp = GameClientMain
					.post("accounts/register")
					.header("content-type", "application/json")
					.body(registerRequest)
					.asJson();
				GameClientMain.handleErrorResponses(resp);
				int status = resp.getStatus();
				System.out.println(resp.getBody());
				if (status == 200) {
					email.setText(remail.getText());
					pass.setText("");
					JOptionPane.showMessageDialog(null,
						    "You can login now.",
						    "Account created",
						    JOptionPane.INFORMATION_MESSAGE);
				}
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}	
		});
		
		add(reg);
	}
}
