/*
 *  psychlops_app_state_OSX.h
 *  Psychlops Standard Library (Universal)
 *
 *  Last Modified 2007/06/22 by Kenchi HOSOKAWA
 *  (C) 2006 Kenchi HOSOKAWA, Kazushi MARUYA and Takao SATO
 */

#include <ApplicationServices/ApplicationServices.h>
#include <CoreServices/CoreServices.h>
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <mach/mach_init.h>
#include <mach/thread_policy.h>

#include "psychlops_app_state_OSX.h"
#include "../../core/ApplicationInterfaces/psychlops_app_info.h"

namespace Psychlops {

	int AppState::createSynchronousProcess(std::string command)
	{
		return 0;
	}

	APIApplicationProperties APIApplicationProperties::startupinfo;

	APIApplicationProperties::APIApplicationProperties() {
		thread_state_[AppState::SLEEP] = kStoppedThreadState;
		thread_state_[AppState::IDLE] = kReadyThreadState;
		thread_state_[AppState::LOW] = kRunningThreadState;
		thread_state_[AppState::NORMAL] = kRunningThreadState;
		thread_state_[AppState::HIGH] = kRunningThreadState;
		MPSetTaskWeight(MPCurrentTaskID(),10000);
	}
	APIApplicationProperties::~APIApplicationProperties() {
	}

	void APIApplicationProperties::setThreadPriority( int priority ) {
		SetThreadState(kCurrentThreadID, thread_state_[priority], kNoThreadID);
	}
	int APIApplicationProperties::getThreadPriority() {
		ThreadState threadState;
		GetThreadState(kCurrentThreadID, &threadState);
		switch(threadState) {
		case kStoppedThreadState:
			return AppState::SLEEP;
		case kReadyThreadState:
			return AppState::IDLE;
		default:
		case kRunningThreadState:
			return AppState::NORMAL;
		}
	}

	
	void stringToPascalString255(std::string from, unsigned char to[255]) {
		int length = (from.length()>254 ? 254 : from.length());
		to[0] = (unsigned char)length;
		for(int i=0; i<length; i++) {
			to[i+1] = from[i];
		}
	}
	
	void AppState::alert(std::string message) {
		unsigned char str[255];
		stringToPascalString255(message, str);
		StandardAlert(kAlertCautionAlert, str, NULL, NULL, NULL);
	}
	
	
}	/*	<- namespace Psycholops 	*/
