# AUTOGENERATED! DO NOT EDIT! File to edit: 00_services.ipynb (unless otherwise specified).

__all__ = ['ServiceManager', 'Service']

# Cell
import time
import urllib.parse
import webbrowser
import requests
from pathlib import Path
from slugify import slugify
from tightai import exceptions
from .exceptions import ArgumentsRequired
from .lookup import Lookup
from .base import BaseObject, base_tightignore
from .conf import CLI_ENDPOINT
from .downloaders import DownloadVersion
from .user import UserObject
from .upload import Uploader
from .utils import sort_by_key, print_dict

# Cell
class ServiceManager(Lookup, BaseObject):
    api = CLI_ENDPOINT
    key = None

    def __str__(self):
        return f"<ServiceManager>"

    def __repr__(self):
        return self.__str__()

    def get(self, slug=None, raw=False):
        if slug == None:
            raise ArgumentsRequired("slug")
        r = self.http_get(f"/services/{slug}/")
        if raw:
            return r
        self.handle_invalid_lookup(r, expected_status_code=200)
        return Service(**r.json())

    def all(self, project_id=None, **kwargs):
        endpoint = f"/services/"
        if len(kwargs.keys()):
            query_string = urllib.parse.urlencode(kwargs)
            endpoint = f"{endpoint}?{query_string}"
        r = self.http_get(endpoint)
        self.handle_invalid_lookup(r, expected_status_code=200)
        return [Service(**x) for x in r.json()['results']]

# Cell
class Service(Lookup, BaseObject):
    '''
    An individual release of any given project.
    '''
    slug = None
    name = ""
    url = None

    def __str__(self):
        return f"<Service {self.name} ({self.slug})>"

    objects = ServiceManager()

    def predict(self, slug=None, json={}, data={}, files={}, params={}, method='POST'):
        if slug == None:
            slug = self.slug
        if slug == None:
            msg = "You must include a service `slug`"
            print(msg)
            raise Exception(msg)
        if slug and not self.url:
            r = self.objects.get(slug=slug, raw=True)
            if r.status_code == 200:
                service_response_data = r.json()
                for k, v in service_response_data.items:
                    setattr(self, k, v)
        if not self.url:
            raise Exception("Invalid service url. Please try again.")
        response =  self.request(method, self.url, json=json, data=data, files=files, params=params)
        headers = response.headers
        contentType = headers.get('content-type') or "text/html"
        is_json  = 'application/json' in contentType
        status_code = response.status_code
        if status_code not in range(200, 299):
            print("Not a valid request.")
        return response