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


import flask
import json
from flask_jwt_extended import jwt_required, get_current_user
from pritunl_dedicated.blueprints import api_subscription_plan
from pritunl_dedicated.models.pritunl_dedicated import SubscriptionPlan
from pritunl_dedicated.extensions import db
from pritunl_dedicated.views.api import filter_to_sqlalchemy, sort_to_sqlalchemy


__author__ = "Adam Schubert"
__date__ = "$18.8.2014 23:33:05$"


@api_subscription_plan.route('', methods=['GET'], defaults={'page': 1})
@api_subscription_plan.route('/page/<int:page>', methods=['GET'])
@jwt_required
def get_subscription_plans(page: int):

    order_by = sort_to_sqlalchemy(
        SubscriptionPlan,
        flask.request.args.get('sort_field'),
        int(flask.request.args.get('sort_order', 1)),
        {
            'name': 'name'
        },
        'created'
    )

    subscriptions = SubscriptionPlan.query.order_by(order_by)

    per_page = int(flask.request.args['per_page']) if 'per_page' in flask.request.args else subscriptions.count()
    filters = json.loads(flask.request.args['filters']) if 'filters' in flask.request.args else {}
    subscriptions_filter = filter_to_sqlalchemy(
        SubscriptionPlan,
        filters,
        {
            'name': 'name'
        }
    )

    paginator = subscriptions.filter(*subscriptions_filter).paginate(page, per_page)

    data_ret = []
    for subscription in paginator.items:
        data_ret.append(subscription.jsonify())

    ret = {
        'has_next': paginator.has_next,
        'has_prev': paginator.has_prev,
        'next_num': paginator.next_num,
        'prev_num': paginator.prev_num,
        'page': paginator.page,
        'pages': paginator.pages,
        'per_page': paginator.per_page,
        'total': paginator.total,
        'data': data_ret,
        'next': flask.url_for('api.subscription_plan.get_subscription_plans', page=paginator.next_num, _external=True),
        'prev': flask.url_for('api.subscription_plan.get_subscription_plans', page=paginator.prev_num, _external=True)
    }

    return flask.jsonify(ret), 200


@api_subscription_plan.route('', methods=['PUT'])
@jwt_required
def set_subscription_plan():
    subscription_plan_id = flask.request.json.get('id')
    name = flask.request.json.get('name')

    subscription_plan_found = SubscriptionPlan.query.filter_by(id=subscription_plan_id).first()
    if not subscription_plan_found:
        return flask.jsonify({'message': 'Subscription plan not found'}), 404

    subscription_plan_name_found = SubscriptionPlan.query.filter_by(name=name).first()
    if subscription_plan_name_found and subscription_plan_name_found != subscription_plan_found:
        return flask.jsonify({'message': 'Subscription plan name found'}), 409

    subscription_plan_found.name = name

    db.session.add(subscription_plan_found)
    db.session.commit()

    return flask.jsonify(subscription_plan_found.jsonify()), 200


@api_subscription_plan.route('', methods=['POST'])
@jwt_required
def create_subscription_plan():
    name = flask.request.json.get('name')

    subscription_plan_found = SubscriptionPlan.query.filter_by(name=name).first()
    if subscription_plan_found:
        return flask.jsonify({'message': 'Subscription plan found'}), 409

    new_subscription_plan = SubscriptionPlan()
    new_subscription_plan.name = name
    db.session.add(new_subscription_plan)
    db.session.commit()

    return flask.jsonify(new_subscription_plan.jsonify()), 200


@api_subscription_plan.route('/<int:subscription_plan_id>', methods=['DELETE'])
@jwt_required
def delete_subscription_plan(subscription_plan_id: int):
    subscription_found = SubscriptionPlan.query.filter_by(id=subscription_plan_id).first()
    if not subscription_found:
        return flask.jsonify({'message': 'Subscription not found'}), 404
    db.session.delete(subscription_found)
    db.session.commit()
    return flask.jsonify(subscription_found.jsonify()), 200


@api_subscription_plan.route('/<int:subscription_plan_id>', methods=['GET'])
@jwt_required
def get_subscription_plan(subscription_plan_id: int):
    subscription_found = SubscriptionPlan.query.filter_by(id=subscription_plan_id).first()
    if not subscription_found:
        return flask.jsonify({'message': 'Subscription not found'}), 404

    return flask.jsonify(subscription_found.jsonify()), 200
