# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function

import requests

from polyaxon_client.api.base import BaseApiHandler
from polyaxon_client.exceptions import AuthenticationError, PolyaxonHTTPError
from polyaxon_client.schemas import CredentialsConfig, UserConfig


class AuthApi(BaseApiHandler):
    """
    Auth/User specific api handler.

    Special case client because of the token is not acquired yet,
    so we do not use shared client functions.
    """
    ENDPOINT = "/users"

    def get_user(self, token=None):
        token = token or self.transport.token
        request_url = self._get_http_url()
        response = self.transport.get(request_url,
                                      headers={"Authorization": "{} {}".format(
                                          self.config.authentication_type, token)})
        try:
            user_dict = response.json()
            response.raise_for_status()
        except Exception:
            if response.status_code == 401:
                raise AuthenticationError(
                    request_url,
                    response,
                    "Invalid Token.\nSee http://docs.polyaxon.com/faqs/authentication/ for help",
                    401)
            raise AuthenticationError(
                request_url,
                response,
                "Login failed.\nSee http://docs.polyaxon.com/faqs/authentication/ for help",
                response.status_code)

        return self.prepare_results(response_json=user_dict, config=UserConfig)

    @staticmethod
    def _get_token(request_url, response):
        try:
            token_dict = response.json()
            response.raise_for_status()
        except Exception:
            if response.status_code == 401:
                raise AuthenticationError(
                    request_url,
                    response,
                    "Invalid credentials.",
                    401)
            raise AuthenticationError(
                request_url,
                response,
                "Login failed.\nSee http://docs.polyaxon.com/faqs/authentication/ for help",
                response.status_code)

        return token_dict.get('token')

    def login(self, credentials):
        credentials = self.validate_config(config=credentials, config_schema=CredentialsConfig)
        request_url = self.build_url(self._get_http_url(), 'token')
        try:
            response = self.transport.session.post(request_url, data=credentials.to_dict())
        except requests.ConnectionError:
            raise PolyaxonHTTPError(
                request_url,
                None,
                "Connection error.",
                None)
        return self._get_token(request_url=request_url, response=response)

    def login_using_ephemeral_token(self, url, ephemeral_token):
        try:
            response = self.transport.session.post(url, {'token': ephemeral_token})
        except requests.ConnectionError:
            raise PolyaxonHTTPError(
                url,
                None,
                "Connection error.",
                None)
        return self._get_token(request_url=url, response=response)

@@ -100,16 +100,53 @@
 quests%0A%0A
+from polyaxon_client import settings%0A
 from pol
@@ -1603,41 +1603,33 @@
     
-@staticmethod%0A    def _get
+def _process
 _token(
+self, 
 requ
@@ -1645,16 +1645,33 @@
 response
+, set_token=False
 ):%0A     
@@ -2238,22 +2238,23 @@
         
-return
+token =
  token_d
@@ -2269,16 +2269,97 @@
 'token')
+%0A        if set_token:%0A            self.config.token = token%0A        return token
 %0A%0A    de
@@ -2383,16 +2383,33 @@
 dentials
+, set_token=False
 ):%0A     
@@ -2873,35 +2873,39 @@
    return self._
-get
+process
 _token(request_u
@@ -2937,16 +2937,37 @@
 response
+, set_token=set_token
 )%0A%0A    d
@@ -2979,13 +2979,18 @@
 gin_
-using
+experiment
 _eph
@@ -3011,109 +3011,761 @@
 elf,
- url, ephemeral_token):%0A        try:%0A            response = self.transport.session.post(url, %7B'token'
+%0A                                         username,%0A                                         project_name,%0A                                         experiment_id,%0A                                         ephemeral_token,%0A                                         set_token=False):%0A        request_url = self.build_url(self._get_http_url('/'),%0A                                     username,%0A                                     project_name,%0A                                     'experiments',%0A                                     experiment_id,%0A                                     'token')%0A        try:%0A            response = self.transport.session.post(%0A                request_url,%0A                headers=%7Bsettings.AuthenticationTypes.EPHEMERAL_TOKEM
 : ep
@@ -3874,16 +3874,24 @@
         
+request_
 url,%0A   
@@ -3989,19 +3989,23 @@
 n self._
-get
+process
 _token(r
@@ -4015,16 +4015,24 @@
 est_url=
+request_
 url, res
@@ -4045,10 +4045,31 @@
 response
+, set_token=set_token
 )%0A

Update login using the ephemeral tokens * Update token processing