#     Copyright (C) 2018 Ipset
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# -*- coding: utf-8 -*-

import platform, traceback, os, time
import xbmc, xbmcvfs, xbmcaddon

ADDON_ID      = 'script.kodi.ipset.defaults'
REAL_SETTINGS = xbmcaddon.Addon(id=ADDON_ID)
ADDON_NAME    = REAL_SETTINGS.getAddonInfo('name')
ADDON_VERSION = REAL_SETTINGS.getAddonInfo('version')

## GLOBALS ##
DEBUG         = REAL_SETTINGS.getSetting('Enable_Debugging') == 'true'
CLEAN         = REAL_SETTINGS.getSetting('Disable_Maintenance') == 'false'
CACHE         = REAL_SETTINGS.getSetting('Disable_Cache') == 'false'

def log(msg, level=xbmc.LOGDEBUG):
    if DEBUG == False and level != xbmc.LOGERROR: return
    if level == xbmc.LOGERROR: msg += ' ,' + traceback.format_exc()
    xbmc.log(ADDON_ID + '-' + ADDON_VERSION + '-' + msg, level)

def install_addon(addon_id):
    try:
        xbmc.executebuiltin('InstallAddon(' + addon_id + ')')
        xbmc.executebuiltin('SendClick(11)')
        log('Try to InstallAddon(' + addon_id + ')', 2)
    except Exception as e:
        xbmc.log("Failed to install %s. Error: %s" % (addon_id, str(e)), xbmc.LOGERROR)
        xbmcgui.Dialog().notification("Addon Install Failed", "Failed to install %s. Please check the log for more details" % (addon_id), xbmcgui.NOTIFICATION_ERROR, 5000)

class Service(object):
    def __init__(self):
        try:
            missing_addons = []
            for pl in ['plugin.video.iptvaddons', 'plugin.video.iptvadulti', 'plugin.video.kod']:
                if not os.path.exists(os.path.join(xbmcvfs.translatePath('special://home/addons'), pl)):
                    missing_addons.append(pl)
                    log("Not Installed %s" % pl, 2)
                else:
                    log("Installed %s" % pl, 2)
            if missing_addons:
                    for addon in missing_addons:
                        install_addon(addon)
        except Exception as e:
            log("Service Failed! " + str(e), xbmc.LOGERROR)
            xbmcgui.Dialog().notification("Service Failed", "An error occurred while trying to install missing addons. Please check the log for more details", xbmcgui.NOTIFICATION_ERROR, 5000)

if __name__ == '__main__': Service()

