/*
 * user.c
 *
 *  Created on: Dec 14, 2010
 *      Author: blackpanther
 */
#include <stdlib.h>
#include <string.h>

#include "logger.h"
#include "utilities.h"

#include "user.h"

#define USER_TEMPLATE "User (id:%3u) :\n\t-login    : %s\n\t-password : %s\n%s"

static
void addGroupToUser(User * user, int groupid, int roleid)
{
	if(user->groups.size < MAX_ITEM)
	{
		user->groups.group[ user->groups.size ][ID]      = groupid;
		user->groups.group[ user->groups.size ][ROLE_ID] = roleid;
		user->groups.size++;
	}
	else
	{
		logMessage(SEVERE,"method : add group to user","maximum reached, can't add more group");
	}
}

static
void setDatabaseId(User* user, unsigned int id)
{
	if( !user->id )
		user->id = createPersistentItem(id);
	else
		user->id->_db_id = id;
}

static
unsigned int getDatabaseId(User* user)
{
	if( user->id )
		return user->id->getId(user->id);
	else
		return 0;
}

static
void setUserLogin(User* user, char* newlogin)
{
	if( user->login )
	{
		free(user->login);
	}

	user->login = (char *)malloc(strlen(newlogin)*sizeof(char));
	strcpy(user->login,newlogin);
}

static
char* getUserLogin(User* user)
{
	return user->login;
}

static
void setUserPassword(User* user, char* newpassword)
{
	if( user->password )
	{
		free(user->password);
	}

	user->password = (char *)malloc(strlen(newpassword)*sizeof(char));
	strcpy(user->password,newpassword);
}

static
char* getUserPassword(User* user)
{
	return user->password;
}


static
char* displayUser(User* user)
{
	int i;
	static char output[MAX_STRING_INPUT];
	char groupsBuffer[MAX_STRING_INPUT];

	memset(output,0,MAX_STRING_INPUT*sizeof(char));

	sprintf(groupsBuffer,"%s","Groups : \n");
	for(i=0;i<user->groups.size;i++)
	{
		sprintf(groupsBuffer,"%s\t- groupid : %3d & roleid : %3d\n",groupsBuffer,user->groups.group[i][ID],user->groups.group[i][ROLE_ID]);
	}

	sprintf(output,USER_TEMPLATE,
			user->getId(user),
			user->login,
			user->password,
			groupsBuffer);

	return output;
}

User* createUserSkeleton() {
	User* entity = NULL;

	entity = (User *)malloc(sizeof(User));

		handleError(
				!entity,
				NULL,
				"method : createUserSkeleton",
				"unable to malloc");

	entity->id       = NULL;
	entity->login    = NULL;
	entity->password = NULL;

	memset(entity->groups.group,0,MAX_ITEM * sizeof(int));
	entity->groups.size = 0;

	entity->addGroup       = addGroupToUser;
    entity->setId          = setDatabaseId;
    entity->getId          = getDatabaseId;
    entity->setLogin       = setUserLogin;
    entity->getLogin       = getUserLogin;
    entity->setPassword    = setUserPassword;
    entity->getPassword    = getUserPassword;
    entity->display        = displayUser;

	return entity;
}

void destroyUser(User* user) {
	destroyPersistentItem(user->id);
	free(user->login);
	free(user->password);
	free(user);
}
