# -*- coding: utf-8 -*-
import flask

from saas.tools.abcd.models.models import db, Account, SaasService
from saas.tools.abcd.models.database_handles import get_instance

saas_api = flask.Blueprint('saas_quota_handles', __name__, url_prefix='/api/saas/')
content_type = 'application/json; charset=utf-8'


def _response(response_data):
    flask.current_app.logger.debug('Response data: %s', response_data)
    return flask.jsonify(response_data)


@saas_api.route('quotas/', methods=['GET'])
def list_quota_accounts():
    """
    SaaS List Quotas method
    """
    accounts_page = db.session.query(Account).all()
    result = [account.as_quota_dict() for account in accounts_page]
    return _response(result)


@saas_api.route('quotas/<abc_id>', methods=['GET'])
def get_quota_account(abc_id):
    """
    Handle for getting quota account.
    :param abc_id: type int
    """
    account = get_instance(db, Account, abc_service_id=abc_id)
    if not account:
        flask.abort(404)
    return _response(account.as_quota_dict())


@saas_api.route('services/<abc_quota_id>', methods=['GET'])
def get_quota_services(abc_quota_id):
    """
    Get saas services by quota_id
    :param abc_quota_id: type int
    """
    service_instances = db.session.query(SaasService).filter_by(abc_service_quota=abc_quota_id).all()
    result = [service.as_dict() for service in service_instances]
    return _response(result)


@saas_api.route('services/', methods=['GET'])
def get_services():
    """
    Get all saas services
    """
    service_instances = db.session.query(SaasService).all()
    result = [service.as_dict() for service in service_instances]
    return _response(result)
