import cookies
from logger import Logger

class SettingsStorage:
    settingsFile = "./conf/settings.txt"
    blacklistFile = "./conf/blacklist.txt"
    cookies = {}
    settings = {}
    blacklist = []
    isLoaded = False

    def __init__(self):
        Logger.info("> Load settings")
        self.settings["sort"] = False
        self.settings["idleOnlyAfterLimit"] = False
        self.settings["timeIdleBatch"] = 1
        self.settings["chromePath"] = ""
        execfile(self.settingsFile, self.settings);
        Logger.params("Sort is on?", self.settings["sort"])
        Logger.params("Idle only games with more than 2 hours played?", self.settings["idleOnlyAfterLimit"])
        Logger.params("Size of batch for time-idling", self.settings["timeIdleBatch"])
        Logger.params("Chrome cookies path:", self.settings["chromePath"])

        Logger.info("> Load cookies")
        self.cookies = cookies.getCookies(self.settings["chromePath"], "steam")

        if not self.checkCookies(self.cookies):
            Logger.warn("smth goes wrong with cookies")
            return
        Logger.info("cookies are loaded")

        Logger.info("> Check blacklist")
        self.loadBlacklist()
        Logger.info(str( len(self.blacklist) ) + " game(s) in blacklist")

        self.isLoaded = True

    def checkCookies(self, cookies):
        if not cookies:
            Logger.error("no cookies are loaded")
            return False
        if not cookies["sessionid"]:
            Logger.error("no session id")
            return False
        if not cookies["steamLogin"]:
            Logger.error("no steam login")
            return False
        if not cookies["steamparental"]:
            Logger.error("no steam parental")
            return False
        return True

    def loadBlacklist(self):
        try:
            with open(self.blacklistFile, 'r') as f:
                lines = f.readlines()
            self.blacklist = [int(s.strip()) for s in lines]
        except:
            self.blacklist = []

    def idleNotPlayedGames(self):
        return not self.settings["idleOnlyAfterLimit"]

    def idleInBatchSize(self):
        return self.settings["timeIdleBatch"]

    def getProfileUrl(self):
        return "http://steamcommunity.com/profiles/" + self.cookies["steamLogin"][:17]

    def getCookies(self):
        cookies = dict(sessionid=self.cookies["sessionid"],
                       steamLogin=self.cookies["steamLogin"],
                       steamparental=self.cookies["steamparental"])
        return cookies

    def isGameInBlacklist(self, appId):
        return appId in self.blacklist