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

"""
    greenbyteapi

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

from greenbyteapi.api_helper import APIHelper
from greenbyteapi.configuration import Configuration
from greenbyteapi.controllers.base_controller import BaseController
from greenbyteapi.http.auth.custom_header_auth import CustomHeaderAuth
from greenbyteapi.models.status_item import StatusItem
from greenbyteapi.exceptions.problem_details_exception import ProblemDetailsException
from greenbyteapi.exceptions.api_exception import APIException

class StatusesController(BaseController):

    """A Controller to access Endpoints in the greenbyteapi API."""


    def get_statuses(self,
                     device_ids,
                     timestamp_start,
                     timestamp_end,
                     category=None,
                     lost_production_signal_id=None,
                     fields=None,
                     sort_by=None,
                     sort_asc=False,
                     page_size=50,
                     page=1,
                     use_utc=False):
        """Does a GET request to /status.

        Gets statuses for multiple devices during the given time period.
        The timestamps are in the time zone configured in the Greenbyte
        Platform.
        Use the useUtc flag to get timestamps in UTC.
        _🔐 This endpoint requires the **Statuses** endpoint permission._
        _This request can also be made using the POST method, 
        with a request to `status.json` and 
        a JSON request body instead of query parameters._

        Args:
            device_ids (list of int): Which devices to get statuses for.
            timestamp_start (datetime): The beginning of the time interval to
                get data for (inclusive), in [RFC 3339, section
                5.6](https://tools.ietf.org/html/rfc3339#section-5.6)
                **date-time** format:  * Timestamps ending with 'Z' are
                treated as UTC. Example: "2020-01-01T00:00:00Z" * Time zone
                (UTC) offset timestamps ending with '+HH:mm'/"-HH:mm" are also
                supported. Example: "2020-01-01T02:00:00-02:00" * Other
                timestamps are treated as being in the time zone configured in
                the Greenbyte Platform. Example: "2020-01-01T00:00:00"  The
                start timestamp **is** included in the time interval: for
                example, to select the full month of March 2020, set
                `timestampStart` to "2020-03-01T00:00:00" and `timestampEnd`
                to "2020-04-01T00:00:00".
            timestamp_end (datetime): The end of the time interval to get data
                for (exclusive), in [RFC 3339, section
                5.6](https://tools.ietf.org/html/rfc3339#section-5.6)
                **date-time** format:  * Timestamps ending with 'Z' are
                treated as UTC. Example: "2020-01-01T00:00:00Z" * Time zone
                (UTC) offset timestamps ending with '+HH:mm'/"-HH:mm" are also
                supported. Example: "2020-01-01T02:00:00-02:00" * Other
                timestamps are treated as being in the time zone configured in
                the Greenbyte Platform. Example: "2020-01-01T00:00:00"  The
                end timestamp is **not** included in the time interval: for
                example, to select the full month of March 2020, set
                `timestampStart` to "2020-03-01T00:00:00" and `timestampEnd`
                to "2020-04-01T00:00:00".
            category (list of StatusCategoryEnum, optional): Which status
                categories to get statuses for.
            lost_production_signal_id (int, optional): Which data signal to
                use for calculating lost production. Defaults to the
                configured default lost production signal.
            fields (list of string, optional): Which fields to include in the
                response. Valid fields are those defined in the `StatusItem`
                schema (See Response Type). By default all fields are
                included.
            sort_by (list of string, optional): Which fields to sort the
                response items by.
            sort_asc (bool, optional): Whether to sort the items in ascending
                order.
            page_size (int, optional): The number of items to return per
                page.
            page (int, optional): Which page to return when the number of
                items exceed the page size.
            use_utc (bool, optional): Set to true to get timestamps in UTC.

        Returns:
            list of StatusItem: Response from the API. A list of statuses with
                related data.

        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 = '/status'
        _query_builder = Configuration.get_base_uri()
        _query_builder += _url_path
        _query_parameters = {
            'deviceIds': device_ids,
            'timestampStart': APIHelper.when_defined(APIHelper.RFC3339DateTime, timestamp_start),
            'timestampEnd': APIHelper.when_defined(APIHelper.RFC3339DateTime, timestamp_end),
            'category': category,
            'lostProductionSignalId': lost_production_signal_id,
            'fields': fields,
            'sortBy': sort_by,
            'sortAsc': sort_asc,
            'pageSize': page_size,
            'page': page,
            'useUtc': use_utc
        }
        _query_builder = APIHelper.append_url_with_query_parameters(_query_builder,
            _query_parameters, Configuration.array_serialization)
        _query_url = APIHelper.clean_url(_query_builder)

        # Prepare headers
        _headers = {
            'accept': 'application/json'
        }

        # Prepare and execute request
        _request = self.http_client.get(_query_url, headers=_headers)
        CustomHeaderAuth.apply(_request)
        _context = self.execute_request(_request)

        # Endpoint and global error handling using HTTP status codes.
        if _context.response.status_code == 400:
            raise ProblemDetailsException('The request cannot be fulfilled due to bad syntax.', _context)
        elif _context.response.status_code == 401:
            raise APIException('The request is missing a valid API key. ', _context)
        elif _context.response.status_code == 403:
            raise APIException('One of the following: * The API key does not authorize access to the requested endpoint because of a missing endpoint permission. * The API key does not authorize access to the requested data. Devices, sites or data signals can be limited. ', _context)
        elif _context.response.status_code == 405:
            raise APIException('The HTTP method is not allowed for the endpoint.', _context)
        elif _context.response.status_code == 429:
            raise ProblemDetailsException('The API key has been used in too many requests in a given amount of time. The following headers will be set in the response: * `X-Rate-Limit-Limit` – The rate limit period (for example   "1m", "12h", or "1d"). * `X-Rate-Limit-Remaining` – The remaining number of requests   for this period. * `X-Rate-Limit-Reset` – The UTC timestamp string (in ISO 8601   format) when the remaining number of requests resets.  The limit is currently 1,000 requests/minute per API key and IP address. ', _context)
        self.validate_response(_context)

        # Return appropriate type
        return APIHelper.json_deserialize(_context.response.raw_body, StatusItem.from_dictionary)

    def get_active_statuses(self,
                            device_ids,
                            category=None,
                            lost_production_signal_id=None,
                            fields=None,
                            sort_by=None,
                            sort_asc=False,
                            page_size=50,
                            page=1,
                            use_utc=False):
        """Does a GET request to /activestatus.

        Gets active statuses for multiple devices.
        The timestamps are in the time zone configured in the Greenbyte
        Platform.
        Use the useUtc flag to get timestamps in UTC.
        _🔐 This endpoint requires the **Statuses** endpoint permission._
        _This request can also be made using the POST method, 
        with a request to `activestatus.json` and 
        a JSON request body instead of query parameters._

        Args:
            device_ids (list of int): Which devices to get statuses for.
            category (list of StatusCategoryEnum, optional): Which status
                categories to get statuses for.
            lost_production_signal_id (int, optional): Which data signal to
                use for calculating lost production. Defaults to the
                configured default lost production signal.
            fields (list of string, optional): Which fields to include in the
                response. Valid fields are those defined in the `StatusItem`
                schema (See Response Type). By default all fields are
                included.
            sort_by (list of string, optional): Which fields to sort the
                response items by.
            sort_asc (bool, optional): Whether to sort the items in ascending
                order.
            page_size (int, optional): The number of items to return per
                page.
            page (int, optional): Which page to return when the number of
                items exceed the page size.
            use_utc (bool, optional): Set to true to get timestamps in UTC.

        Returns:
            list of StatusItem: Response from the API. A list of active
                statuses with related data.

        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 = '/activestatus'
        _query_builder = Configuration.get_base_uri()
        _query_builder += _url_path
        _query_parameters = {
            'deviceIds': device_ids,
            'category': category,
            'lostProductionSignalId': lost_production_signal_id,
            'fields': fields,
            'sortBy': sort_by,
            'sortAsc': sort_asc,
            'pageSize': page_size,
            'page': page,
            'useUtc': use_utc
        }
        _query_builder = APIHelper.append_url_with_query_parameters(_query_builder,
            _query_parameters, Configuration.array_serialization)
        _query_url = APIHelper.clean_url(_query_builder)

        # Prepare headers
        _headers = {
            'accept': 'application/json'
        }

        # Prepare and execute request
        _request = self.http_client.get(_query_url, headers=_headers)
        CustomHeaderAuth.apply(_request)
        _context = self.execute_request(_request)

        # Endpoint and global error handling using HTTP status codes.
        if _context.response.status_code == 400:
            raise ProblemDetailsException('The request cannot be fulfilled due to bad syntax.', _context)
        elif _context.response.status_code == 401:
            raise APIException('The request is missing a valid API key. ', _context)
        elif _context.response.status_code == 403:
            raise APIException('One of the following: * The API key does not authorize access to the requested endpoint because of a missing endpoint permission. * The API key does not authorize access to the requested data. Devices, sites or data signals can be limited. ', _context)
        elif _context.response.status_code == 405:
            raise APIException('The HTTP method is not allowed for the endpoint.', _context)
        elif _context.response.status_code == 429:
            raise ProblemDetailsException('The API key has been used in too many requests in a given amount of time. The following headers will be set in the response: * `X-Rate-Limit-Limit` – The rate limit period (for example   "1m", "12h", or "1d"). * `X-Rate-Limit-Remaining` – The remaining number of requests   for this period. * `X-Rate-Limit-Reset` – The UTC timestamp string (in ISO 8601   format) when the remaining number of requests resets.  The limit is currently 1,000 requests/minute per API key and IP address. ', _context)
        self.validate_response(_context)

        # Return appropriate type
        return APIHelper.json_deserialize(_context.response.raw_body, StatusItem.from_dictionary)
