#ifndef YDWESyncIncluded
#define YDWESyncIncluded

library YDWESync initializer onInit
    globals
        private gamecache m_gc
        private boolean   m_mutex_state = false
    endglobals

	private function IsLivingPlayer takes player p returns boolean
		return (GetPlayerSlotState(p) == PLAYER_SLOT_STATE_PLAYING) /*
		*/ and (GetPlayerController(p) == MAP_CONTROL_USER)
	endfunction
	private function GetLivingfPlayer takes nothing returns player
		local integer i = 0
		loop
			exitwhen IsLivingPlayer(Player(i)) or i >= 11
			set i = i + 1
		endloop
		return Player(i)
	endfunction
    
    public function Lock takes nothing returns nothing
        loop
            if not m_mutex_state then
                set m_mutex_state = true
                return 
            endif
            call TriggerSleepAction(0.2)
        endloop
    endfunction
    
    public function Unlock takes nothing returns nothing
        set m_mutex_state = false
    endfunction
    
    public function Join takes player p returns nothing
        if GetLocalPlayer() == p then
            call StoreInteger(m_gc, "-", "-", 'YDWE')
        endif
        call TriggerSyncStart()
        if GetLocalPlayer() == p then 
            call SyncStoredInteger(m_gc, "-", "-")  
        endif
        call StoreInteger(m_gc, "-", "-", 0)
        call TriggerSyncReady()        
        loop
            if 'YDWE' == GetStoredInteger(m_gc, "-", "-") then
                return 
            endif
            call TriggerSleepAction(0.2)
        endloop
    endfunction
    
    public function Set takes string table, string key, integer value returns nothing
        call StoreInteger(m_gc, table, key, value)            
    endfunction
    
    public function Get takes string table, string key returns integer
        return GetStoredInteger(m_gc, table, key)            
    endfunction
    
    public function Start takes nothing returns nothing
        call TriggerSyncStart()            
    endfunction
    
    public function Ready takes nothing returns nothing
        call TriggerSyncReady()            
    endfunction
    
    public function Send takes string table, string key returns nothing
        call SyncStoredInteger(m_gc, table, key)             
    endfunction
    
	private function onInit takes nothing returns nothing
		call FlushGameCache(InitGameCache("@"))
		set m_gc = InitGameCache("@")
	endfunction
endlibrary
#endif
