#include "context/AbstractCallerController.h"
#include "context/CallerData.h"
#include "util/simpleobject/AgDate.h"
#include <boost/thread/locks.hpp>

std::set<CallerController*>  AbstractCallerController::CONTROLLERS;
boost::mutex AbstractCallerController::mutex;

AbstractCallerController::AbstractCallerController(CallerDataPtr callerData):CallerController()
{  
    loggedIn = false;
    this->callerData = callerData;


    {
        boost::lock_guard<boost::mutex> lock(mutex);
        CONTROLLERS.insert(this);
    }
}

bool AbstractCallerController::isLoggedIn()
{
    return loggedIn;
}

bool AbstractCallerController::isPermissionCheckingEnabled()
{
    return true;
}

PermissionCachePtr AbstractCallerController::getPermissionCache()
{
    return PermissionCachePtr();
}

CallerDataPtr AbstractCallerController::getCallerData()
{
	return callerData;
}

std::map<AgString, AgString> AbstractCallerController::getProperties()
{
    return properties;
}

void AbstractCallerController::setLoggedIn(bool loggedIn)
{
    this->loggedIn = loggedIn;
}

void AbstractCallerController::sendFeedback(int level, const AgString & message)
{
    UNUSED(level);
    UNUSED(message);
}

std::list<CallerController*> AbstractCallerController::getControllers()
{
   std::list<CallerController*>  list;

   {
        boost::lock_guard<boost::mutex> lock(mutex);
        for(std::set<CallerController*>::iterator  it = CONTROLLERS.begin(); it != CONTROLLERS.end(); it++)
        {
            list.push_front(*it);
        }
   }
  return list;
}

AgString AbstractCallerController::toString()
{
    AgString str1 = (loggedIn ? "logged in" : "not logged in");
    AgString str2 = " (" + str1 + ")";
    return (!type.empty()) ? type : typeid(this).name() + str2;
}

PermissionsPtr AbstractCallerController::getPermissions()
{
    return PermissionsPtr();
}

AgString AbstractCallerController::getUsername()
{
    return username;
}

void AbstractCallerController::setUsername(const AgString & username)
{
    this->username = username;
}

AgString AbstractCallerController::getInheritedUsername()
{
    return "";
}

AgString AbstractCallerController::getEffectiveUsername()
{
   AgString inheritedUsername = getInheritedUsername();
   return !inheritedUsername.empty() ? inheritedUsername : getUsername();
}

AgString AbstractCallerController::getType()
{
    return type;
}

void AbstractCallerController::setType(const AgString & type)
{
    this->type = type;
}

AgString AbstractCallerController::getAddress()
{
    return address;
}

void AbstractCallerController::setAddress(const AgString & address)
{
    this->address = address;
}

void AbstractCallerController::login(const AgString & username, const AgString & inheritedUsername, PermissionsPtr permissons)
{
    setUsername(username);
    UNUSED(inheritedUsername);
    UNUSED(permissons);
}

AgDate AbstractCallerController::getCreationTime()
{
    return creationTime;
}

void AbstractCallerController::logout()
{
}



