# coding: utf-8

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

import requests

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


class SandboxResource(object):
    PROPERTIES = {'skynet_id', 'http', 'description', 'rights', 'url', 'file_name', 'sources', 'state', 'arch', 'time',
                  'owner', 'attributes', 'for_parent', 'size', 'type', 'md5'}

    def __str__(self):
        return 'SandboxResource({}:{}):https://sandbox.yandex-team.ru/resource/{}/view'.format(
            self.type, self.id, self.id
        )

    def __init__(self, sandbox, resource_id, task=None):
        """
        :type sandbox: sandbox.common.rest.Client
        :type resource_id: int
        :type task: SandboxTask
        """
        self.sandbox_client = sandbox
        self.id = resource_id
        self._task = task
        self._info = {}

    @classmethod
    def from_resource_info(cls, sandbox, resource_info):
        resource = cls(sandbox=sandbox, resource_id=resource_info['id'],
                       task=SandboxTask(sandbox=sandbox, task_id=resource_info['task']['id']))
        resource._info = resource_info
        return resource

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

    @property
    def ready(self):
        """
        :return: resource ready status
        :rtype: bool
        """
        return self.state == 'READY'

    def __getattribute__(self, name):
        if name in object.__getattribute__(self, 'PROPERTIES'):
            info = object.__getattribute__(self, '_info')
            if info.get(name, None) is None or info.get('state', 'NOT_READY') == 'NOT_READY':
                self.update_info()
            return self._info[name]
        else:
            return object.__getattribute__(self, name)

    @property
    def task(self):
        if self._task is None:
            if self._info.get('task', None) is None:
                self.update_info()
            self._task = SandboxTask(self.sandbox_client, self._info['task']['id'])
        return self._task

    @property
    def content_skynet_url(self):
        return self.skynet_id

    @property
    def content_http_url(self):
        return self.http['proxy']

    @property
    def content(self):
        return requests.get(self.content_http_url).content

    @property
    def json_content(self):
        return requests.get(self.content_http_url).json()

    def nanny_resource_info(self):
        return {
            'resource_id': str(self.id),
            'resource_type': self.type,
            'task_id': str(self.task.id),
            'task_type': self.task.type
        }
