import os
from functools import partial

from siege import game
from siege.log import Log
from siege.util import seconds, Timer


class ObservedFile(object):
    def __init__(self, path, handler):
        self.path = path
        self.time = os.stat(path).st_mtime
        self.handler = handler

    def updateTime(self):
        time = os.stat(self.path).st_mtime
        changed = self.time != time
        self.time = time
        return changed


class DeveloperSystem(object):
    NAME = "developer"
    POLL_FREQUENCY = seconds(1)

    def getName(self):
        return self.NAME

    def __init__(self):
        self.files = []
        self.enabled = True
        game.events['world_loaded'].listen(self.reset)
        self.pollTimer = Timer(DeveloperSystem.POLL_FREQUENCY)

    def reset(self, world):
        self.files = []
        for content in game.content.getContents():
            self.addObserver(content.data().path, partial(self.handleContent, content.data()))

    def update(self, frameTime):
        self.pollTimer.update(frameTime)
        if self.pollTimer.expired():
            #Cleanup removed files
            self.files[:] = [f for f in self.files if os.path.exists(f.path)]
            #Update observed file times and call handler for changed files
            [f.handler(f.path) for f in self.files if f.updateTime()]
            game.content.discover("mods")
            self.pollTimer.reset(DeveloperSystem.POLL_FREQUENCY)

    def addObserver(self, path, handler):
        if os.path.exists(path):
            self.files.append(ObservedFile(path, handler))
        else:
            Log.debug("Requested observation of nonexistant path: {}".format(path))

    def handleContent(self, path, content):
        Log.info("Reloading Content: {}".format(path))
        game.entity.reloadContentEntities(content)
