# -*- coding: utf-8 -*-
#------------------------------------------------------------
# smytvshow
# Cache Manager
# http://smystero.dlinkddns.org/smytvshow/
#------------------------------------------------------------

import os, time

import xbmcvfs

import logger,config
if config.use_mysql:
    from mysqlinterface import sql_manager as sql
else:
    from sql import sql_manager as sql

class CacheManager():

    def __init__(self):
        logger.debug("start...")
        self.forced = False
        self.path = os.path.join(config.get_plugin_dir(), "cache")
        self.file = os.path.join(self.path, "status.txt")
        self.exists()
        self.stat = xbmcvfs.Stat(self.file)
        logger.debug("end...")

    def exists(self):
        if not xbmcvfs.exists(self.path):
            xbmcvfs.mkdirs(self.path)
            self.clear()
        else:
            if not xbmcvfs.exists(self.file):
                self.clear()
        return

    def touch(self):
        try:
            f = xbmcvfs.File(self.file, 'w')
            try:
                f.write("Touched")
            finally:
                f.close()
        except:
            pass

        return

    def force(self):
        self.forced = True
        self.clear()
        self.forced = False

    def validate(self):
        dirs, files = xbmcvfs.listdir(self.path)
        for file in files:
            try:
                currTime = time.time()
                os.utime(os.path.join(self.path, file), (currTime, currTime))
            except Exception, e:
                logger.error(e.message)
                pass
        self.touch()

    def check(self):
        if self.is_old(self.stat.st_mtime()):
            self.clear()

    def clear(self):
        self.clearTrakt()
        if self.forced | (config.get_setting("use_cache") == "true"):
            dirs, files = xbmcvfs.listdir(self.path)
            for file in files:
                self.check_age(os.path.join(self.path, file))
        self.touch()

    def clearTrakt(self):
        s = sql.SqlManager()
        s.del_trakt()
        s.add_trakt()
        del s

    def is_old(self, m_time):
        return (time.time() - m_time) / 60 / 60 > 6

    def check_age(self, file):
        ret = True;
        t_stat = xbmcvfs.Stat(file)
        if self.forced | self.is_old(t_stat.st_mtime()):
            xbmcvfs.delete(file)
            ret = False
        return ret

    def get_cached_file(self, file):
        ret = False;
        full_file_path = os.path.join(self.path, file)
        if xbmcvfs.exists(full_file_path):
            ret = self.check_age(full_file_path)
        return ret, full_file_path