# downloader.py
# -*- coding: utf-8 -*-
import os
import time
import xbmc
import xbmcgui
import xbmcaddon
from urllib.request import build_opener, install_opener, urlretrieve

addon = xbmcaddon.Addon()
icon = addon.getAddonInfo('icon')

def infoDialog(message, heading=None, iconimage=None, time=3000, sound=False):
    """
    Notificação de status de download.
    """
    if heading is None:
        heading = addon.getAddonInfo('name')

    if iconimage is None:
        iconimage = icon
    elif iconimage == 'INFO':
        iconimage = xbmcgui.NOTIFICATION_INFO
    elif iconimage == 'WARNING':
        iconimage = xbmcgui.NOTIFICATION_WARNING
    elif iconimage == 'ERROR':
        iconimage = xbmcgui.NOTIFICATION_ERROR

    xbmcgui.Dialog().notification(heading, message, iconimage, time, sound=sound)

def _pbhook(numblocks, blocksize, filesize, url, dp):
    """
    Hook para mostrar progresso no DialogProgress.
    """
    try:
        percent = int(min((numblocks * blocksize * 100) / filesize, 100))
        currently_downloaded = float(numblocks * blocksize) / (1024 * 1024)
        kbps_speed = (numblocks * blocksize) / (time.time() - _pbhook.start_time) if _pbhook.start_time else 0
        eta_seconds = (filesize - numblocks * blocksize) / kbps_speed if kbps_speed > 0 else 0
        kbps_speed = kbps_speed / 1024
        total_mb = float(filesize) / (1024 * 1024)

        msg = f'{currently_downloaded:.2f} MB de {total_mb:.2f} MB\n'
        msg += f'[COLOR yellow]Speed:[/COLOR] {kbps_speed:.02f} Kb/s '
        mins, secs = divmod(int(eta_seconds), 60)
        msg += f'[COLOR yellow]Time left:[/COLOR] {mins:02d}:{secs:02d}'
        dp.update(percent, msg)

    except Exception:
        dp.update(100)

    if percent >= 100:
        infoDialog('Download completo.', iconimage='INFO')
    elif dp.iscanceled():
        dp.close()
        raise Exception('Download cancelado pelo usuário.')

def download_py3(url, dest, dp):
    """
    Baixa usando urlretrieve (Python 3).
    """
    opener = build_opener()
    opener.addheaders = [
        ('User-Agent', 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) '
                       'AppleWebKit/537.36 (KHTML, like Gecko) '
                       'Chrome/100.0.4896.75 Mobile Safari/537.36')
    ]
    install_opener(opener)

    # registra início do hook
    _pbhook.start_time = time.time()
    urlretrieve(url, dest, lambda nb, bs, fs, url=url: _pbhook(nb, bs, fs, url, dp))

def download(url, name, dest, dp=None):
    """
    Ponto de entrada: se não existir DialogProgress, cria um.
    """
    global _pbhook
    if dp is None:
        dp = xbmcgui.DialogProgress()
        dp.create(f'Baixando {name}...', 'Por favor, aguarde...')

    dp.update(0)
    try:
        download_py3(url, dest, dp)
    except Exception:
        # remove arquivo parcial, caso ocorra erro ou cancelamento
        try:
            os.remove(dest)
        except:
            pass
        raise
