# -*- coding: utf-8 -*-

"""
restapisdk

This file was automatically generated by APIMATIC v3.0 (
 https://www.apimatic.io ).
"""

from restapisdk.api_helper import APIHelper
from restapisdk.configuration import Server
from restapisdk.controllers.base_controller import BaseController
from restapisdk.models.create_table_response import CreateTableResponse
from restapisdk.exceptions.error_response_exception import ErrorResponseException


class DatabaseController(BaseController):

    """A Controller to access Endpoints in the restapisdk API."""
    def __init__(self, config, auth_managers, call_back=None):
        super(DatabaseController, self).__init__(config, auth_managers, call_back)

    def get_databases(self):
        """Does a GET request to /api/rest/v2/database.

        Note: This endpoint is applicable only for on-prem deployments 
         To list all the databases in Falcon, use this endpoint.

        Returns:
            list of string: Response from the API. List of databases in
                Falcon

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """

        # Prepare query URL
        _url_path = '/api/rest/v2/database'
        _query_builder = self.config.get_base_uri()
        _query_builder += _url_path
        _query_url = APIHelper.clean_url(_query_builder)

        # Prepare headers
        _headers = {
            'accept': 'application/json',
            'Content-Type': self.config.content_type
        }

        # Prepare and execute request
        _request = self.config.http_client.get(_query_url, headers=_headers)
        # Apply authentication scheme on request
        self.apply_auth_schemes(_request, 'global')

        _response = self.execute_request(_request)

        # Endpoint and global error handling using HTTP status codes.
        if _response.status_code == 500:
            raise ErrorResponseException('Operation failed or unauthorized request', _response)
        self.validate_response(_response)

        decoded = APIHelper.json_deserialize(_response.text)

        return decoded

    def get_schemas(self,
                    database):
        """Does a GET request to /api/rest/v2/database/schema.

        Note: This endpoint is applicable only for on-prem deployments 
         To list all the schemas in a database in Falcon, use this endpoint.

        Args:
            database (string): Name of the Falcon database

        Returns:
            list of string: Response from the API. List of schemas in Falcon
                Database provided in the request

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """

        # Prepare query URL
        _url_path = '/api/rest/v2/database/schema'
        _query_builder = self.config.get_base_uri()
        _query_builder += _url_path
        _query_parameters = {
            'database': database
        }
        _query_builder = APIHelper.append_url_with_query_parameters(
            _query_builder,
            _query_parameters
        )
        _query_url = APIHelper.clean_url(_query_builder)

        # Prepare headers
        _headers = {
            'accept': 'application/json',
            'Content-Type': self.config.content_type
        }

        # Prepare and execute request
        _request = self.config.http_client.get(_query_url, headers=_headers)
        # Apply authentication scheme on request
        self.apply_auth_schemes(_request, 'global')

        _response = self.execute_request(_request)

        # Endpoint and global error handling using HTTP status codes.
        if _response.status_code == 500:
            raise ErrorResponseException('Operation failed or unauthorized request', _response)
        self.validate_response(_response)

        decoded = APIHelper.json_deserialize(_response.text)

        return decoded

    def get_tables(self,
                   database,
                   schema):
        """Does a GET request to /api/rest/v2/database/table.

        Note: This endpoint is applicable only for on-prem deployments. 
         To list all the tables in a schema of a database in Falcon, use this
         endpoint.

        Args:
            database (string): Name of the Falcon database
            schema (string): Name of the schema in Falcon database

        Returns:
            list of string: Response from the API. List of tables in the
                schema of Falcon Database provided in the request

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """

        # Prepare query URL
        _url_path = '/api/rest/v2/database/table'
        _query_builder = self.config.get_base_uri()
        _query_builder += _url_path
        _query_parameters = {
            'database': database,
            'schema': schema
        }
        _query_builder = APIHelper.append_url_with_query_parameters(
            _query_builder,
            _query_parameters
        )
        _query_url = APIHelper.clean_url(_query_builder)

        # Prepare headers
        _headers = {
            'accept': 'application/json',
            'Content-Type': self.config.content_type
        }

        # Prepare and execute request
        _request = self.config.http_client.get(_query_url, headers=_headers)
        # Apply authentication scheme on request
        self.apply_auth_schemes(_request, 'global')

        _response = self.execute_request(_request)

        # Endpoint and global error handling using HTTP status codes.
        if _response.status_code == 500:
            raise ErrorResponseException('Operation failed or unauthorized request', _response)
        self.validate_response(_response)

        decoded = APIHelper.json_deserialize(_response.text)

        return decoded

    def create_table(self,
                     body):
        """Does a POST request to /api/rest/v2/database/table/create.

        Note: This endpoint is applicable only for on-prem deployments. 
         To create a table in Falcon, use this endpoint.

        Args:
            body (ApiRestV2DatabaseTableCreateRequest): TODO: type description
                here.

        Returns:
            CreateTableResponse: Response from the API. Details of the table
                created

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """

        # Prepare query URL
        _url_path = '/api/rest/v2/database/table/create'
        _query_builder = self.config.get_base_uri()
        _query_builder += _url_path
        _query_url = APIHelper.clean_url(_query_builder)

        # Prepare headers
        _headers = {
            'accept': 'application/json',
            'Content-Type': 'application/json'
        }

        # Prepare and execute request
        _request = self.config.http_client.post(_query_url, headers=_headers, parameters=APIHelper.json_serialize(body))
        # Apply authentication scheme on request
        self.apply_auth_schemes(_request, 'global')

        _response = self.execute_request(_request)

        # Endpoint and global error handling using HTTP status codes.
        if _response.status_code == 500:
            raise ErrorResponseException('Operation failed or unauthorized request', _response)
        self.validate_response(_response)

        decoded = APIHelper.json_deserialize(_response.text, CreateTableResponse.from_dictionary)

        return decoded

    def run_query(self,
                  body):
        """Does a POST request to /api/rest/v2/database/table/runquery.

        Note: This endpoint is applicable only for on-prem deployments. 
         To run a TQL statement in Falcon, use this endpoint. 
         You can run only following type of statements - Table DDL alter and
         Table rows update and delete.

        Args:
            body (ApiRestV2DatabaseTableRunqueryRequest): TODO: type
                description here.

        Returns:
            list of object: Response from the API. TQL statements included in
                the request and the status of each statement

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """

        # Prepare query URL
        _url_path = '/api/rest/v2/database/table/runquery'
        _query_builder = self.config.get_base_uri()
        _query_builder += _url_path
        _query_url = APIHelper.clean_url(_query_builder)

        # Prepare headers
        _headers = {
            'accept': 'application/json',
            'Content-Type': 'application/json'
        }

        # Prepare and execute request
        _request = self.config.http_client.post(_query_url, headers=_headers, parameters=APIHelper.json_serialize(body))
        # Apply authentication scheme on request
        self.apply_auth_schemes(_request, 'global')

        _response = self.execute_request(_request)

        # Endpoint and global error handling using HTTP status codes.
        if _response.status_code == 500:
            raise ErrorResponseException('Operation failed or unauthorized request', _response)
        self.validate_response(_response)

        decoded = APIHelper.json_deserialize(_response.text)

        return decoded
