from otree.api import Currency as c, currency_range
from ._builtin import Page, WaitPage
from .models import Constants

import json
import urllib
from django.conf import settings
from django.contrib import messages


#################################################
#################################################
class CaptchaPage(Page):

    def is_displayed(self):
        return self.round_number == 1

    def vars_for_template(self):
        message = ""
        if self.player.failed_captcha:
            message = "Please check the captcha"
        return{
            'error_message': message,
        }

    def post(self):
        request = self.request
        # Begin reCAPTCHA validation
        recaptcha_response = request.POST.get('g-recaptcha-response')
        url = 'https://www.google.com/recaptcha/api/siteverify'
        values = {
            'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
            'response': recaptcha_response
        }
        data = urllib.parse.urlencode(values).encode()
        req = urllib.request.Request(url, data=data)
        response = urllib.request.urlopen(req)
        result = json.loads(response.read().decode())
        # End reCAPTCHA validation '''

        if result['success']:
            self.player.failed_captcha = False
            return super().post()
        else:
            messages.error(request, 'Invalid reCAPTCHA. Please try again.')
            self.player.failed_captcha = True
            return self.get()


#################################################
#################################################
class PresPage(Page):
    pass


class NormPage(Page):
    form_model = 'player'
    form_fields = ['norm_choice']


class MerciPage(Page):
    def vars_for_template(self):
        return{
            'total_earnings': self.player.participant.payoff_plus_participation_fee(),
        }


page_sequence = [
    CaptchaPage,
    PresPage,
    NormPage,
]
