import graphene
from graphene import relay

from oauth.hep_client import HepClient, HepClientException
from oauth.user_signup_login_handler import check_and_create_licenses, create_role_for_user


class Coupon(relay.ClientIDMutation):
    class Input:
        coupon_code = graphene.String()

    success = graphene.Boolean()

    @classmethod
    def mutate_and_get_payload(cls, root, info, **kwargs):
        coupon_code = kwargs.get('coupon_code').strip()
        hep_client = HepClient()

        try:
            hep_id = info.context.user.hep_id
        except AttributeError:
            raise Exception('not_authenticated')

        try:
            response = hep_client.coupon_redeem(coupon_code, hep_id)
        except HepClientException:
            raise Exception('unknown_error')

        if not response:
            raise Exception('invalid_coupon')

        license, error_msg = check_and_create_licenses(hep_client, info.context.user)

        # todo fail if no license
        if error_msg:
            raise Exception(error_msg)

        create_role_for_user(info.context.user, license.for_role.key)

        return cls(success=True)


class CouponMutations:
    redeem_coupon = Coupon.Field()
