# -*- coding: utf-8 -*-
# RD Tools - Export / Import + ZIP Tools (Speed + ETA)
# ---------------------------------------------------

import os
import time
import xbmcgui
import xbmcvfs
from modules import utils, zip_tools


# =============================================================================
# DIRECTORY COPY WITH PROGRESS + SPEED / ETA
# =============================================================================

def _copy_with_progress(src_folder, dst_folder):
    dp = xbmcgui.DialogProgressBG()
    dp.create("Copying Files", os.path.basename(src_folder))

    try:
        all_files = []
        for root, dirs, files in xbmcvfs.walk(src_folder):
            for f in files:
                src_file = utils.join_path(root, f)
                rel_path = os.path.relpath(src_file, src_folder)
                dst_file = utils.join_path(dst_folder, rel_path)
                all_files.append((src_file, dst_file))

        total = len(all_files)
        if total == 0:
            dp.close()
            xbmcgui.Dialog().ok("No Files", "Nothing to copy.")
            return

        start_time = time.time()
        processed_bytes = 0
        total_bytes = 0
        for src, _ in all_files:
            try:
                stat = xbmcvfs.Stat(src)
                total_bytes += stat.st_size() if hasattr(stat, "st_size") else 0
            except Exception:
                pass

        for i, (src_file, dst_file) in enumerate(all_files, 1):
            dst_parent = os.path.dirname(dst_file)
            if not xbmcvfs.exists(dst_parent):
                xbmcvfs.mkdirs(dst_parent)

            file_size = 0
            try:
                info = xbmcvfs.Stat(src_file)
                file_size = info.st_size() if hasattr(info, "st_size") else 0
            except Exception:
                pass

            utils.copy_vfs(src_file, dst_file)
            processed_bytes += file_size

            utils.progress_speed_eta(dp, i, total, processed_bytes, total_bytes, start_time, os.path.basename(src_file), "Copying")

        dp.close()
        total_time = time.time() - start_time
        utils.notify("Copy Complete", f"Copied {total} files in {total_time:.1f}s")
    except Exception as e:
        dp.close()
        xbmcgui.Dialog().ok("Copy Failed", str(e))


# =============================================================================
# FILE & DIRECTORY EXPORT / IMPORT
# =============================================================================

def export_file():
    src = utils.browse_file_kodi_root("Select file to export (Kodi root)")
    if not src: return
    dst_folder = utils.browse_folder_device_fs("Select destination folder (device filesystem)")
    if not dst_folder: return
    dst = utils.join_path(dst_folder, os.path.basename(src))
    utils.copy_vfs(src, dst)
    utils.notify("Export", f"File exported:\n{os.path.basename(src)}")


def import_file():
    src = utils.browse_file_device_fs("Select file to import (device filesystem)")
    if not src: return
    dst_folder = utils.browse_folder_kodi_root("Select destination folder (Kodi root)")
    if not dst_folder: return
    dst = utils.join_path(dst_folder, os.path.basename(src))
    utils.copy_vfs(src, dst)
    utils.notify("Import", f"File imported:\n{os.path.basename(src)}")


def export_directory():
    src_folder = utils.browse_folder_kodi_root("Select directory to export (Kodi root)")
    if not src_folder: return
    dst_folder = utils.browse_folder_device_fs("Select destination (device filesystem)")
    if not dst_folder: return
    dst = utils.join_path(dst_folder, os.path.basename(src_folder.rstrip('/')))
    _copy_with_progress(src_folder, dst)


def import_directory():
    src_folder = utils.browse_folder_device_fs("Select directory to import (device filesystem)")
    if not src_folder: return
    dst_folder = utils.browse_folder_kodi_root("Select destination (Kodi root)")
    if not dst_folder: return
    dst = utils.join_path(dst_folder, os.path.basename(src_folder.rstrip('/')))
    _copy_with_progress(src_folder, dst)


# =============================================================================
# MENU: EXPORT / IMPORT + ZIP TOOLS
# =============================================================================

def export_import_menu():
    options = [
        "📁 Export Directory (Kodi root → device fs)",
        "📁 Import Directory (device fs → Kodi root)",
        "📄 Export File / ZIP (Kodi root → device fs)",
        "📄 Import File / ZIP (device fs → Kodi root)",
        "🗜️  ZIP Tools (Create / Extract / Download)",
        "⬅️ Back"
    ]

    while True:
        sel = xbmcgui.Dialog().select("Export / Import & ZIP Tools", options)
        if sel == -1 or sel == 5:
            break
        elif sel == 0:
            export_directory()
        elif sel == 1:
            import_directory()
        elif sel == 2:
            export_file()
        elif sel == 3:
            import_file()
        elif sel == 4:
            zip_tools.zip_menu()
