# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django import forms
from django.core.exceptions import ValidationError

from core.models import Reporter
from core.utils import external_userinfo_by_login
from core.utils import BlackboxUserError


__all__ = ['BlackboxUserForm']


class BlackboxUserForm(forms.Form):
    username = forms.CharField(max_length=128)

    def clean(self):
        login = self.cleaned_data.get('username')
        reporter = self._get_reporter_by_contract(login)
        if reporter is None:
            blackbox_user = self._get_blackbox_user(login)
            reporter = self._get_reporter(blackbox_user.uid)
        self.cleaned_data['username'] = reporter
        return self.cleaned_data

    def _get_blackbox_user(self, login):
        try:
            blackbox_user = external_userinfo_by_login(login)
        except BlackboxUserError:
            raise ValidationError('%s does not exist' % login)
        return blackbox_user

    def _get_reporter(self, uid):
        try:
            reporter = Reporter.objects.get(uid=uid)
        except Reporter.DoesNotExist:
            raise ValidationError('User uid %s is not registered in BugBounty' % uid)
        return reporter

    def _get_reporter_by_contract(self, contract_id):
        reporter = None
        if contract_id:
            try:
                reporter = Reporter.objects.get(balance_contract_id=contract_id)
            except Reporter.DoesNotExist:
                pass
        return reporter
