# coding: utf-8

from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

import logging

from saas.library.python.sandbox.task import SandboxTask
from saas.library.python.sandbox.enums import SchedulerStatus


class SandboxScheduler(object):
    LOGGER = logging.getLogger(__name__)

    class Schedule(object):
        __slots__ = ('repetition', 'start_time', 'fail_on_error', 'retry', 'sequential_run', )
        STR_FORMAT = 'SandboxScheduler.Schedule({}, start_time={}, fail_on_error={}, retry_interval={}, sequential_run={})'

        def __init__(self, interval, start_time=None, fail_on_error=False, retry_interval=None, sequential_run=False,):
            self.repetition = {'interval': interval}
            self.start_time = start_time
            self.fail_on_error = fail_on_error
            self.retry = {'ignore': True, 'interval': retry_interval}
            self.sequential_run = sequential_run

        def dict(self):
            base_dict = {
                'repetition': self.repetition,
                'start_time': self.start_time.isoformat() if self.start_time is not None else None,
                'fail_on_error': self.fail_on_error,
                'retry': self.retry,
                'sequential_run': self.sequential_run
            }
            return {k: v for k, v in base_dict.items() if v is not None}

        def __str__(self):
            return self.STR_FORMAT.format(self.repetition['interval'], self.start_time, self.fail_on_error,
                                          self.retry and self.retry['interval'], self.sequential_run)

    @classmethod
    def from_scheduler_info(cls, sandbox, scheduler_info):
        scheduler = cls(sandbox, scheduler_info['id'])
        scheduler._info = scheduler_info
        return scheduler

    def __init__(self, sandbox, scheduler_id):
        self.sandbox_client = sandbox
        self.id = scheduler_id
        self._info = None

    def __repr__(self):
        return 'SandboxScheduler({})'.format(self.id)

    def __str__(self):
        return 'SandboxScheduler(id={}, status={})'.format(self.id, self.status)

    def dict(self):
        if self._info is None:
            self.update_info()
        return self._info

    def __getattribute__(self, name):
        if name in {'fail_on_error', 'sequential_run'}:
            return self.dict()[name]
        else:
            return object.__getattribute__(self, name)

    def update_info(self):
        self._info = self.sandbox_client.scheduler[self.id].read()

    def start(self):
        self.sandbox_client.batch.schedulers.start.update([self.id])

    def stop(self):
        self.sandbox_client.batch.schedulers.stop.update([self.id])

    @property
    def last_task(self):
        last_task = self.dict()['task']['last']
        return SandboxTask.from_task_info(self.sandbox_client, last_task) if last_task else None

    @property
    def status(self):
        return SchedulerStatus(self.dict()['status'])
