
import os
import re

import xbmc
import xbmcaddon
import xbmcvfs
import requests

try:
    from sqlite3 import dbapi2 as database
except:
    from pysqlite2 import dbapi2 as database
addonInfo = xbmcaddon.Addon().getAddonInfo
dataPath = xbmcvfs.translatePath(addonInfo('profile'))
databaseFile = os.path.join(dataPath, 'settings.db')
from resources.lib import PhantomCommon
cm = PhantomCommon.common()



def log(msg):
    xbmc.log(msg, level=xbmc.LOGINFO)


def writeData(param, value, query):
    try:
        record = (param, value, query)
        xbmcvfs.mkdir(dataPath)
        dbcon = database.connect(os.path.join(dataPath, 'settings.db'))
        dbcur = dbcon.cursor()
        dbcur.execute(
            '''CREATE TABLE IF NOT EXISTS params2 (param INT, value TEXT, query varchar(10), UNIQUE(param))''')
        dbcur.execute("DELETE FROM params2 WHERE param = %s" % (record[0]))
        dbcur.execute("INSERT INTO params2 Values (%s, %s, %s)" % record)
        dbcon.commit()
    except:
        return


def readParam(param):
    try:
        dbcon = database.connect(databaseFile)
        dbcur = dbcon.cursor()
        dbcur.execute("SELECT value FROM params2 WHERE param = %s" % (param))
        view = dbcur.fetchone()
        return view[0]
    except Exception as e:
        return


def readParamQuery(param):
    try:
        dbcon = database.connect(databaseFile)
        dbcur = dbcon.cursor()
        dbcur.execute("SELECT query FROM params2 WHERE param = %s" % (param))
        view = dbcur.fetchone()
        return view[0]
    except:
        return


def getConfig(conf):
    try:
        phantom_user = xbmcaddon.Addon().getSetting('phantom_user')
        phantom_pass = xbmcaddon.Addon().getSetting('phantom_pass')
        query_data = {'url': 'http://www.phantom-kodi.cba.pl/%s.php' % conf, 'use_post': True, 'return_data': True}
        response = cm.getURLRequestData(query_data, {'version': addonInfo('version'), 'phantom_user': phantom_user, 'phantom_pass': phantom_pass})
        match = re.compile('param=(.*?)value=(.*?)query=(.*?)</th>', re.DOTALL).findall(response)
        for i in range(len(match)):
            writeData(match[i][0], match[i][1], match[i][2])
    except Exception as e:
        return


def getQuery(param):
    query = readParamQuery(param)
    try:
        query_data = {'url': 'http://www.phantom-kodi.cba.pl/query003.php', 'use_post': True, 'return_data': True}
        response = cm.getURLRequestData(query_data, {'query': query})
        query = re.compile('query:(.+?)<>', flags=re.S).findall(response)
        return query[0]
    except:
        return


def writeViewed(id, info, save_viewed):
    try:
        record = (id, info.replace("'", ""))
        xbmcvfs.mkdir(dataPath)
        dbcon = database.connect(os.path.join(dataPath, 'movies.db'))
        dbcur = dbcon.cursor()
        dbcur.execute('''CREATE TABLE IF NOT EXISTS viewed (id_stream TEXT, info TEXT)''')
        dbcur.execute("DELETE FROM viewed WHERE id_stream = '" + id + "'")
        dbcur.execute('''INSERT INTO viewed Values ('%s', '%s')''' % record)
        dbcur.execute(
            'DELETE FROM viewed where`_rowid_` < (SELECT MIN(`_rowid_`) from viewed where `_rowid_` in (SELECT `_rowid_` FROM `viewed` ORDER BY `_rowid_` DESC limit %s))' % save_viewed)
        dbcon.commit()
    except:
        return


def readViewed():
    try:
        dbcon = database.connect(os.path.join(dataPath, 'movies.db'))
        dbcur = dbcon.cursor()
        dbcur.execute("SELECT * FROM viewed ORDER BY `_rowid_` DESC")
        arr = dbcur.fetchall()
        return arr
    except:
        return

def setSetting(name, value):
    try:
        record = (name, str(value))
        xbmcvfs.mkdir(dataPath)
        dbcon = database.connect(os.path.join(dataPath, 'settings.db'))
        dbcur = dbcon.cursor()
        dbcur.execute('''CREATE TABLE IF NOT EXISTS settings (name TEXT, value TEXT, UNIQUE(name))''')
        dbcur.execute("DELETE FROM settings WHERE name = '" + name + "'")
        dbcur.execute('''INSERT INTO settings Values ('%s', '%s')''' % record)
        dbcon.commit()
    except:
        return

def getSetting(name):
    try:
        dbcon = database.connect(databaseFile)
        dbcur = dbcon.cursor()
        dbcur.execute("SELECT value FROM settings WHERE name = '" + name + "'")
        view = dbcur.fetchone()
        return view[0]
    except Exception as e:
        return
