import sys
import os
import xbmc
import copy
import fscache
import re
from datetime import timedelta
from datetime import datetime
from datetime import date
import time
from requests import requests
from  epg_db import epg_db

__author__ = 'Alexander Bonelis'

__version__ = '0.10'

IPTV_DOMAIN = 'api.sovok.tv'
IPTV_API = 'http://%s/v2.3/json/%%s' % IPTV_DOMAIN
IPTV_API_HTTPS = 'https://%s/v2.3/json/%%s' % IPTV_DOMAIN
ARCHIVE_TIME_PREFIX = 5 * 60 * 1000

TIMZONE_REGEXP = re.compile(r'((?P<hours>[-+]\d\d):)?((?P<minutes>\d+?):)?((?P<seconds>\d\d))?')
CACHE_TIME_CHANNEL_LIST = 60 * 24
CACHE_TIME_STREAMERS_LIST = 180
CACHE_TIME_CHANNEL_EPG = 60 * 24
CACHE_TIME_DAY_EPG = 60 * 24
SESSION_TIMEOUT_MIN = 180
TIME_ZONES = [u'-12:00:00',
              u'-11:00:00',
              u'-10:00:00',
              u'-09:00:00',
              u'-08:00:00',
              u'-07:00:00',
              u'-06:00:00',
              u'-05:00:00',
              u'-04:00:00',
              u'-03:00:00',
              u'-02:00:00',
              u'-01:00:00',
              u'+00:00:00',
              u'+01:00:00',
              u'+02:00:00',
              u'+03:00:00',
              u'+04:00:00',
              u'+05:00:00',
              u'+06:00:00',
              u'+07:00:00',
              u'+08:00:00',
              u'+09:00:00',
              u'+10:00:00',
              u'+11:00:00',
              u'+12:00:00',
              u'+13:00:00',
              u'+14:00:00'
              ]
STORAGE_KEY_LOGIN_INFO = u'loginInfo'

# channel_list_cache_it = fscache.FSCache(xbmc.translatePath('special://temp/relict.sovok.tv/channelList'), days=1)
# epg_cache_it = fscache.FSCache(xbmc.translatePath('special://temp/relict.sovok.tv/epg'), days=7)
# ch_epg_cache_it = fscache.FSCache(xbmc.translatePath('special://temp/relict.sovok.tv/ch_epg'), days=7)
# login_info_cache_it = fscache.FSCache(xbmc.translatePath('special://temp/relict.sovok.tv/login_info'), days=1)
settings_cache_it = fscache.FSCache(xbmc.translatePath('special://temp/relict.sovok.tv/settings'), hours=1)


class SovokApi:
    def __init__(self, plugin):
        self.plugin = plugin
        self.day_epg_cache = None
        self.db = epg_db()

    def gen_ua(self):
        ver_info = sys.version_info
        python_version = '%s.%s.%s' % (ver_info[0], ver_info[1], ver_info[2])
        osname = '%s %s; %s' % (os.name, sys.platform, python_version)

        is_xbmc = 'Relict-XBMC'
        if getattr(xbmc, "nonXBMC", None) is not None:
            is_xbmc = 'Relict-nonXBMC'

        ua = '%s/%s (%s; %s)  iptv/%s user/%s' % (
            is_xbmc, xbmc.getInfoLabel('System.BuildVersion').split(" ")[0], xbmc.getInfoLabel('System.BuildVersion'),
            osname, __version__, '---')
        ua = 'Relict-XBMC/16.1-RC2 (16.1-RC2 Git:20160328-be20e8a; nt win32; 2.7.8)  iptv/0.10 user/---'
        self.plugin.log('[sovok.TV] UA: %s' % ua)
        return ua

    def get_login_info(self):
        return self.db.get_login_info()

    def set_login_info(self, login_info):
        self.db.set_login_info(login_info)

    def is_authenticated(self):
        login_info = self.get_login_info()
        if login_info is not None:
            login_time = login_info[u'login_time']
            login_time += timedelta(minutes=SESSION_TIMEOUT_MIN)
            if login_time < datetime.now():  # Session TimeOut
                self.plugin.log('Sessions timeout -> clean session', xbmc.LOGWARNING)
                self.db.clear_login_info()
                return False
            else:
                return True
        else:
            return False

    def clear_cache(self):
        self.plugin.log('Cleaning cache ... ')
        # channel_list_cache_it.purge()
        # epg_cache_it.purge()
        # ch_epg_cache_it.purge()
        self.db.clear()
        settings_cache_it.purge()

    def is_login_changed(self):
        login_info = self.get_login_info()
        if login_info is not None:
            return \
                login_info[u'login'] != self.plugin.get_setting('login') \
                and \