# -*- coding: utf-8 -*-
# EPG background service for plugin.video.parrottv
# Regenerates epg.xml automatically every hour if older than 12h

import os
import time
import xbmc
import xbmcaddon
import xbmcvfs

ADDON = xbmcaddon.Addon()
ADDON_ID = ADDON.getAddonInfo('id')
ADDON_FOLDER = xbmcvfs.translatePath('special://home/addons/' + ADDON_ID)
USERDATA_FOLDER = xbmcvfs.translatePath('special://home/userdata/addon_data/' + ADDON_ID)

EPG_MAX_AGE = 43200  # 12 hours
CHECK_INTERVAL = 3600  # 1 hour


def _get_epg_source():
    val = ADDON.getSetting("epgSource") or "0"
    idx = int(val) if val.isdigit() else 0
    if idx == 0:
        return "default", ""
    elif idx == 1:
        return "openepg", ""
    elif idx == 2:
        return "custom", ADDON.getSetting("epgUrl") or ""
    return "default", ""


def _ensure_epg_service():
    from resources.utils.epg import update_epg
    from resources.utils.channels import genList

    epg_path = os.path.join(USERDATA_FOLDER, "epg.xml")
    tag_path = os.path.join(USERDATA_FOLDER, ".epg_source")
    raw_path = os.path.join(USERDATA_FOLDER, "epg_raw.xml")

    source, source_url = _get_epg_source()
    source_tag = "%s|%s" % (source, source_url)

    if os.path.isfile(epg_path):
        file_age = time.time() - os.path.getmtime(epg_path)
        if file_age < EPG_MAX_AGE:
            return

    if os.path.isfile(raw_path):
        os.remove(raw_path)

    try:
        update_epg(USERDATA_FOLDER, genList(ADDON_FOLDER), source=source, source_url=source_url)
        with open(tag_path, 'w', encoding='utf-8') as f:
            f.write(source_tag)
    except Exception as e:
        pass


class EPGService(xbmc.Monitor):
    def run(self):
        while not self.abortRequested():
            if self.waitForAbort(CHECK_INTERVAL):
                break
            if ADDON.getSetting("epgEnabled") == "true":
                _ensure_epg_service()


if __name__ == "__main__":
    service = EPGService()
    service.run()
