import xbmc
import xbmcgui
import os

from resources.libs.common.config import CONFIG
from resources.libs.common import directory
from resources.libs.common import logging
from resources.libs.common import tools

def install_from_kodi(plugin):
    import time

    installed_cond = 'System.HasAddon({0})'.format(plugin)
    visible_cond = 'Window.IsTopMost(yesnodialog)'

    if xbmc.getCondVisibility(installed_cond):
        logging.log('Already installed ' + plugin, level=xbmc.LOGDEBUG)
        return True

    logging.log('Installing ' + plugin, level=xbmc.LOGDEBUG)
    xbmc.executebuiltin('InstallAddon({0})'.format(plugin))

    clicked = False
    start = time.time()
    timeout = 20
    while not xbmc.getCondVisibility(installed_cond):
        if time.time() >= start + timeout:
            logging.log('Timed out installing', level=xbmc.LOGDEBUG)
            return False

        xbmc.sleep(500)
		
        if xbmc.getCondVisibility(visible_cond) and not clicked:
            logging.log('Dialog to click open', level=xbmc.LOGDEBUG)
            xbmc.executebuiltin('SendClick(yesnodialog, 11)')
            clicked = True
        else:
            logging.log('...waiting', level=xbmc.LOGDEBUG)

    logging.log('Installed {0}!'.format(plugin), level=xbmc.LOGDEBUG)
    return True

##############################################################
#                                                            #
#  Copyright (C) 2025 SGKodi / Kodi Unlimited Support Group  #
#                                                            #
##############################################################