
import logging
import os
import sys
from time import time

import distro
import psutil

from hawkSoar.version import __VERSION__
from hawkSoar.common.logger import get_logger


class WorkloadStatistic:

    def __init__(self, config=None, api=None, component='ingest'):
        self.config = config
        self.component = component
        self.api = api
        self.platform_information = self._get_platform_information()
        self.logging = get_logger()
        self.logging.debug('{}: Online'.format(self.component))

    def shutdown(self):
        self.logging.debug(
            '{}: shutting down -> set offline message'.format(self.component))
        # self.api send_statistic
        # self.api.update_statistic(self.component, {'status': 'offline', 'last_update': time()})

    def update(self, ingest_workload=None, contain_workload=None, match_workload=None, decision_workload=None, investigate_workload=None, notify_workload=None, record_workload=None, recover_workload=None, utility_workload=None):
        stats = {
            'name': self.component,
            'status': 'online',
            'last_update': time(),
            'system': self._get_system_information(),
            'platform': self.platform_information,
        }

        if ingest_workload:
            stats['ingest'] = ingest_workload
        if contain_workload:
            stats['contain'] = contain_workload
        if match_workload:
            stats['match'] = match_workload
        if decision_workload:
            stats['decision'] = decision_workload
        if investigate_workload:
            stats['investigate'] = investigate_workload
        if notify_workload:
            stats['notify'] = notify_workload
        if record_workload:
            stats['record'] = record_workload
        if investigate_workload:
            stats['recover'] = recover_workload
        if utility_workload:
            stats['utility'] = utility_workload

        # self.api.update_statistic(self.component, stats)

    def _get_system_information(self):
        memory_usage = psutil.virtual_memory()
        try:
            disk_usage = psutil.disk_usage(
                self.config['data_storage']['firmware_file_storage_directory'])
        except Exception:
            disk_usage = psutil.disk_usage('/')
        try:
            cpu_percentage = psutil.cpu_percent()
        except Exception:
            cpu_percentage = 'unknown'

        result = {
            'cpu_cores': psutil.cpu_count(logical=False),
            'virtual_cpu_cores': psutil.cpu_count(),
            'cpu_percentage': cpu_percentage,
            'load_average': ', '.join(str(x) for x in os.getloadavg()),
            'memory_total': memory_usage.total,
            'memory_used': memory_usage.used,
            'memory_percent': memory_usage.percent,
            'disk_total': disk_usage.total,
            'disk_used': disk_usage.used,
            'disk_percent': disk_usage.percent
        }
        return result

    @staticmethod
    def _get_platform_information():
        operating_system = ' '.join(distro.linux_distribution()[0:2])
        python_version = '.'.join(str(x) for x in sys.version_info[0:3])
        version = __VERSION__
        return {
            'os': operating_system,
            'python': python_version,
            'version': version
        }
