# -*- coding: utf-8 -*-
import asyncio
import datetime
import logging

import aiojobs.aiohttp

from homehub_backend.defs import kServiceUptime
from homehub_backend.lib.services import BaseService, ServiceData

LOGGER = logging.getLogger('homehub.services.uptime')


class UptimeService(BaseService):
    KIND = kServiceUptime
    IS_GLOBAL = True

    def __init__(self, app, instance, characteristics):
        super(UptimeService, self).__init__(app, instance, characteristics)
        self.uptime = 0
        self.job = None

    def update_uptime(self):
        delta = datetime.datetime.now() - self.app['STARTUP_TS']
        self.uptime = delta.seconds

    async def current_data(self):
        return ServiceData(data=self.uptime)

    async def worker(self):
        while True:
            await asyncio.sleep(60)
            self.update_uptime()
            await self.notify()

            if self.job.closed:
                break

    async def start(self):
        LOGGER.debug('UptimeService.start()')
        if not self.job:
            self.update_uptime()
            scheduler = aiojobs.aiohttp.get_scheduler_from_app(self.app)
            self.job = await scheduler.spawn(self.worker())

    async def stop(self):
        LOGGER.debug('UptimeService.stop()')

    async def shutdown(self):
        LOGGER.debug('UptimeService.shutdown()')
        if self.job is not None and not self.job.closed:
            await self.job.close()
