#!/usr/bin/env python
# -*- coding: utf-8 -*-

import requests
import simplejson
import logging


class SandboxAPI(object):
    """
    Main class for Sandbox requests.
    """
    API_URL = 'https://sandbox.yandex-team.ru/api/v1.0'
    ARCH = ['linux', 'any']

    def _get_task_list(self, sandbox_task_type, sandbox_resource_type, status, release_type, limit, timeout=60):
        """
        Get last N tasks with specified type with specified status.
        :param sandbox_task_type: type str
        :param status: type str
        :param release_type: type str
        :param limit: type str or int
        :return: type dict
        """
        resp = requests.get('%s/task?type=%s&resource_type=%s&status=%s&release_type=%s&limit=%s&hidden=true'
                            % (self.API_URL, sandbox_task_type, sandbox_resource_type, status, release_type, str(limit)),
                            timeout=timeout)
        logging.debug(str(resp.status_code) + ' ' + resp.url)
        return resp.json().get('items', '')

    def _get_resources(self, sandbox_id):
        """
        Get list of resources of specified task.
        :param sandbox_id: type str
        :return: type dict
        """
        resp = requests.get('%s/task/%s/resources' % (self.API_URL, sandbox_id))
        return resp.json().get('items', '')

    def get_resource(self, resource_id):
        """
        Get resource information.
        :param resource_id: type str
        :return: type dict
        """
        resp = requests.get('%s/resource/%s' % (self.API_URL, resource_id))
        return resp.json()

    def get_target_resource(self, sandbox_id, resource_type):
        """
        Get target resource.
        :param sandbox_id: type str
        :param resource_type: type str
        :return: type str
        """
        resources = self._get_resources(sandbox_id)
        for resource in resources:
            if resource['type'] == resource_type and resource['arch'] in self.ARCH:
                return str(resource['id'])

    def get_last_release(self, sandbox_task_type, resource_type, status='RELEASED', release_type='stable', limit=10):
        """
        Get target task id.
        :param sandbox_task_type: type str
        :param resource_type: type str
        :param status: type str
        :param release_type:  type str
        :param limit: type int
        :return: type str
        """
        max_retry_c = 3
        try_num = 0
        while try_num < max_retry_c:
            try:
                task_list = self._get_task_list(sandbox_task_type, resource_type, status, release_type, limit)
                for task in task_list:
                    target_resource = self.get_target_resource(task['id'], resource_type)
                    if target_resource:
                        return str(task['id']), target_resource
                break
            except simplejson.scanner.JSONDecodeError:
                logging.exception('Sandbox probably not available or resource not found by limit')
            finally:
                try_num += 1
        return None, None
