# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - recaptcha support

    Based heavily on the textcha support in textcha.py

    @copyright: 2011 by Steve McIntyre
    @copyright: 2018 by d42
    @license: GNU GPL, see COPYING for details.
"""
import json
import urllib
import urllib2
from textwrap import dedent

from MoinMoin import log

logging = log.getLogger(__name__)


class ReCaptcha(object):
    """ Recaptcha support """

    VERIFY_URL = "https://www.google.com/recaptcha/api/siteverify"

    def __init__(self, request):
        """ Initialize the Recaptcha setup.

            @param request: the request object
        """
        self.request = request
        self.user_info = request.user.valid and request.user.name or request.remote_addr

        self.site_key = getattr(request.cfg, "recaptcha_site_key", None)
        self.secret_key = getattr(request.cfg, "recaptcha_secret_key", None)

    def is_enabled(self):
        """ check if we're configured, i.e. we have a key
        """
        return self.site_key and self.secret_key

    def check_answer_from_form(self, form=None):
        form = self.request.form if form is None else form

        if not self.is_enabled():
            return True

        return self._submit(
            response=form.get("g-recaptcha-response"),
            remoteip=self.request.remote_addr
        )

    def _submit(self, response, remoteip):

        def encode_if_necessary(s):
            return s.encode("utf-8") if isinstance(s, unicode) else s

        data = urllib.urlencode({
            "secret": encode_if_necessary(self.secret_key),
            "response":  encode_if_necessary(response),
            "remoteip":  encode_if_necessary(remoteip),
        })

        request = urllib2.Request(
            url=self.VERIFY_URL,
            data=data,
            headers={"Content-type": "application/x-www-form-urlencoded"}
        )

        try:
            resp = urllib2.urlopen(request)
            http_code = resp.getcode()
            resp_json = json.loads(resp.read())
            return resp_json["success"] if http_code == 200 else False
        except urllib2.URLError as e:
            logging.exception(e)
            return False
        finally:
            resp.close()

    def render(self, form=None):
        """ Checks if ReCaptchas are enabled and returns HTML for one,
            or an empty string if they are not enabled.

            @return: unicode result html
        """
        if not self.is_enabled():
            return u""

        return dedent(u"""
            <script src='//www.google.com/recaptcha/api.js'></script>
            <div class="g-recaptcha" data-sitekey="{SITE_KEY}"></div>
        """.format(SITE_KEY=self.site_key))
