import logging
import platform
import re
import shutil
import socket
import time

import cpuinfo
import psutil
from django.conf import settings
from django.template.defaultfilters import filesizeformat
from django.utils import timesince

from core.utils import fmt_input, dtnow

_log = logging.getLogger(__name__)


def get_console_version():
    return getattr(settings, 'SITE_INFO')['version']


def get_machine_name():
    pc_name = socket.gethostname()
    pc_name = re.sub('\.local$', '', pc_name)
    return pc_name


def get_description():
    # TODO: Currently taking the name of the console. Think about what "short description" can be
    return getattr(settings, 'SITE_INFO')['name']


def get_operating_system():
    return platform.system()


def get_cpu_model():
    return cpuinfo.get_cpu_info()['brand']


def get_server_time():
    return fmt_input(dtnow(local=True).time())


def get_uptime():
    uptime = int(time.time() - psutil.boot_time())
    converted_awake_time = timesince.timesince(dtnow(-(uptime / 86400)))
    return converted_awake_time


def get_disk_usage():
    total, used, free = shutil.disk_usage("/")

    total = filesizeformat(total)
    free = filesizeformat(free)
    used = filesizeformat(used)
    return {'disk_total': total, 'disk_free': free, 'disk_used': used}


def get_cpu_total():
    return psutil.cpu_percent()


def get_mem():
    """
    Get memory usage

    :return: Dict with mem_total and mem_used

    """
    gb_used = filesizeformat(psutil.virtual_memory().used)
    gb_total = filesizeformat(psutil.virtual_memory().total)

    return {'mem_total': gb_total, 'mem_used': gb_used}
