# -*- coding: utf-8 -*-
#
# ITerativ GmbH
# http://www.iterativ.ch/
#
# Copyright (c) 2019 ITerativ GmbH. All rights reserved.
#
# Created on 2019-10-08
# @author: chrigu <christian.cueni@iterativ.ch>
import graphene
from django.contrib.auth import login
from graphene import relay

# from core.hep_client import HepClient, HepClientException
from core.models import AdminData
from oauth.user_signup_login_handler import handle_user_and_verify_products, UNKNOWN_ERROR, NO_VALID_LICENSE


class Registration(relay.ClientIDMutation):
    class Input:
        confirmation_key = graphene.String()
        user_id = graphene.Int()

    success = graphene.Boolean()
    message = graphene.String()


    @classmethod
    def mutate_and_get_payload(cls, root, info, **kwargs):
        confirmation_key = kwargs.get('confirmation_key')
        user_id = kwargs.get('user_id')

        # hep_client = HepClient()
        # admin_token = AdminData.objects.get_admin_token()

        # try:
        #     hep_client.customer_activate(confirmation_key, user_id)
        #     user_data = hep_client.customers_by_id(admin_token, user_id)
        #     # double check if user has verified his email. If the "confirmation" field is present, the email address
        #     # is not verified.
        #     if 'confirmation' in user_data:
        #         return cls.return_fail_registration_msg('invalid_key')
        # except HepClientException:
        #     return cls.return_fail_registration_msg('unknown_error')
        #
        # user, status_msg = handle_user_and_verify_products(user_data)

        # if user:
        #     login(info.context, user)
        #
        # if status_msg:
        #     if status_msg == NO_VALID_LICENSE:
        #         return cls(success=True, message=NO_VALID_LICENSE)
        #     else:
        #         return cls.return_fail_registration_msg(status_msg)

        return cls(success=True, message='success')

    @classmethod
    def return_fail_registration_msg(cls, message):
        if message == UNKNOWN_ERROR:
            raise Exception(message)

        return cls(success=False, message=message)


class RegistrationMutations:
    registration = Registration.Field()
