package com.murerz.elemister.handler;

import java.util.Random;

import com.murerz.elemister.IncomeCommand;

public class LoginHandler extends HandlerAdapter {

	private Random rnd = new Random();
	private String login;
	private String nick;
	private String version = "Elemister";

	public static LoginHandler create() {
		return new LoginHandler();
	}

	public LoginHandler login(String login) {
		this.login = login;
		return this;
	}

	public LoginHandler nick(String nick) {
		this.nick = nick;
		return this;
	}

	public LoginHandler version(String version) {
		this.version = version;
		return this;
	}

	@Override
	public void in(IncomeCommand command) {
		String cmd = command.getCmd();
		if ("433".equals(cmd)) {
			getClient().out("nick " + randomLogin());
			return;
		}
		if ("001".equals(cmd)) {
			nick = command.getParams();
			return;
		}
	}

	private String randomLogin() {
		return new StringBuilder(50).append(nick).append(rnd.nextInt(10000)).toString();
	}

	@Override
	public void init() {
		getClient().out("USER " + login + " 8 * :" + version);
		getClient().out("NICK " + nick);
	}

	public String getNick() {
		return nick;
	}

}
