var $ = jQuery;
const getElement = (id) => document.getElementById(id);
const ws = new WebSocket('ws://bwc.ryanpandya.com/socket');
var username = "unnamed";
var pId = 0;
const threshold = 10;
var cards = [];
const timeFormat = 'h:mm a [PDT]'

ws.onopen = (moot) => {
    var urlParams = new URLSearchParams(window.location.search);
    console.log('Connected to websocket.');
    username = urlParams.get('username');
    UIkit.notification({
	message: 'Connected!',
	status: 'success',
	pos: 'bottom-center',
	timeout: 1000
    });
    if(username == null || username == ""){
	window.location = "/";
    }    
    else{
    }
    
};

const addMessage = (e) => {
    var self_marker = "";
    if(e.pId == pId){
	self_marker = "self";
    }
    $("ul#chatbox").append(
	'<li class="message uk-margin-top">\
                <p class="uk-text-muted uk-text-small uk-margin-small">\
                  <span class="uk-float-right uk-margin-right">'+e.timestamp+'</span>\
                  <span class="uk-text-primary uk-text-bold username '+self_marker+'" pId='+e.pId+'>'+e.username+'</span>\
                <p style="font-size:12px;">'+e.message+'</p>\
                </p>\
              </li>'
    );
}

ws.onmessage = (event) => {
    event = JSON.parse(event.data); 
    switch(event.type){
    case 'init':
	if(event.mode == "error"){
	    window.location = window.origin + "?error=username";
	}
	console.log(">> Initializing game...");
	pId = event.id;
	console.log("You are in the game as '" + username + "' (Player " + pId + ").");
	getElement("username").value = username;
    	event.messages.forEach(function(e){
	    addMessage(e);
	});
	break;
    case 'changeUsername':
	console.log('Got an updated username: Player %s is now "%s".', event.pId, event.username);
	$("span.username[pId='"+event.pId+"']").text(event.username);
	break;
    case 'error':
	console.log(">> Error: " + event.content);
	if(event.err_username){
	    $("#username").val(event.err_username);
	    const url = window.location.origin + window.location.pathname;
	    history.pushState({},
			      "rename",
			      url + "?username=" + err_username
			     );
	}
	UIkit.notification({
	    message: event.content,
	    status: 'warning',
	    pos: 'bottom-center',
	    timeout: 1000
	});
	break;
    case 'notification':
	console.log(">> Notification: " + event.content);
	UIkit.notification({
	    message: event.content,
	    status: 'success',
	    pos: 'bottom-center',
	    timeout: 1000
	});
	break;
    case 'message':
	console.log(">> Got a message.");	
	addMessage(event);
	break;
    default:
	console.log('Unknown event. Pasting:');
	console.log(event);
    }
    
};

const changeUsername = (name) => {
    packet = {
	"type": "changeUsername",
	"pId": pId,
	"username": name
    }
    console.log("Changing username to: '"+name+"'");
    username = name;
    ws.send(JSON.stringify(packet));    
};

const notice = (message) => {
UIkit.notification({
	message: message,
	status: 'primary',
	pos: 'bottom-center',
	timeout: 2000
    });    
}
    
const error = (message) => {
    UIkit.notification({
	message: message,
	status: 'danger',
	pos: 'bottom-center',
	timeout: 2000
    });    
}

const urlify = (text) => {
    var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
    //var urlRegex = /(https?:\/\/[^\s]+)/g;
    return text.replace(urlRegex, function(url,b,c) {
	var url2 = (c == 'www.') ?  'http://' +url : url;
	return '<a href="' +url2+ '" target="_blank">' + url + '</a>';
    }) 
};

const submitMessage = () => {
    message = $("#message").val();
    if(message.trim()){
	const timestamp = new Date();
	packet = {
	    "type": "message",
	    "pId": pId,
	    "username": username,
	    "message": urlify(message.trim()),
	    "timestamp": new Date()
	}
	console.log("Sending message.");
	ws.send(JSON.stringify(packet));
	$("#message").val("");
    }};

$().ready(function() {
    $("#toggle_chat").on('click', function(e){
	$(this).closest("li").toggleClass("uk-active");
    });

    $("#username").keydown(function(e){
	if(e.keyCode === 13){
	    changeUsername(this.value);
	};    
    });
    $("#username").focusout(function(e){
	changeUsername(this.value);
    });
    $("#message").keyup(function(e){
	if(e.keyCode === 13){
	    submitMessage();
	};
    });

    $("a#toggle_play").on('click', function(e){
	if(cards.length < threshold){
	    UIkit.notification({
		message: "You probably want at least "+ threshold +" cards before you can start playing.",
		status: 'danger',
		pos: 'bottom-center',
		timeout: 50000
	    });
	}
    });

    $("#submitCard").on('click', function(e){
	submitCard();
    });
    $("#newCard").on('click', function(e) {
	clearCard();
    });
    
});
