import graphene
from django.contrib.auth import logout
from django.utils.timezone import now
from graphene import relay

from oauth.hep_client import HepClient, HepClientException
from oauth.models import OAuth2Token
from oauth.user_signup_login_handler import create_role_for_user
from users.models import License


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.redeem_coupon(coupon_code, hep_id, request=info.context)
        except HepClientException:
            raise Exception('unknown_error')

        if not response:
            raise Exception('invalid_coupon')

        product = hep_client.entry_to_product(response['data'], now(), 'coupon')

        if not product:
            raise Exception('non_myskillbox_product')

        license = License.objects.create_license_for_role(info.context.user, product['activated'], product['raw'],
                                                          product['license']['edition'],
                                                          product['order_id'], product['isbn'])

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

        return cls(success=True)


class CouponMutations:
    redeem_coupon = Coupon.Field()


class Logout(graphene.Mutation):
    success = graphene.Boolean()

    def mutate(self, info):
        # log user out from myskillbox even if hep logout fails
        try:
            token = OAuth2Token.objects.get(user=info.context.user)
            hep_client = HepClient()
            try:
                hep_client.logout(request=info.context)
            except Exception as e:
                pass

            token.delete()

        except OAuth2Token.DoesNotExist:
            pass

        logout(info.context)
        return Logout(success=True)


class OauthMutations(object):
    logout = Logout.Field()
    coupon = Coupon.Field()

