# -*- coding: utf-8 -*-
import binascii
import urllib.parse
import random
import threading
import math
from threading import Timer


def format_info_hash(info_hash):
    return binascii.hexlify(urllib.parse.unquote_to_bytes(info_hash))

def format_info_hash_compact(info_hash):
    formated = format_info_hash(info_hash).decode()
    return formated[:4] + ".." + formated[-4:]

def bool_2_Y_N(val):
    return 'Y' if val else 'N'

def get_random_ratio(min: int, max: int):
    if min == max:
        return min
    return random.randrange(min * 1000, max * 1000) / 1000

def convert_size(size_bytes):
   if size_bytes == 0:
       return "0B"
   size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
   i = int(math.floor(math.log(size_bytes, 1024)))
   p = math.pow(1024, i)
   s = round(size_bytes / p, 2)
   return "%s %s" % (s, size_name[i])

def format_timedelta_to_HHMMSS(td):
    td_in_seconds = td.total_seconds()
    hours, remainder = divmod(td_in_seconds, 3600)
    minutes, seconds = divmod(remainder, 60)
    hours = int(hours)
    minutes = int(minutes)
    seconds = int(seconds)
    if minutes < 10:
        minutes = "0{}".format(minutes)
    if seconds < 10:
        seconds = "0{}".format(seconds)
    return "{}:{}:{}".format(hours, minutes,seconds)

def object_to_dict(obj):
    if isinstance(obj, list):
        return [object_to_dict(e) for e in obj]
    if isinstance(obj, dict):
        return {key: object_to_dict(value) for key, value in obj.items()}
    if hasattr(obj, "__dict__"):
        return {key: object_to_dict(value) for key, value in obj.__dict__.items() if not callable(value) and not key.startswith("_")}
    return obj


def set_interval(func, sec):
    def func_wrapper():
        try:
            func()
        finally:
            set_interval(func, sec)
    t = Timer(sec, func_wrapper)
    t.name = f"Timer: every {sec}s {func.__name__}"
    t.start()
    return t