# encoding: utf8
import logging

from pyramid.httpexceptions import HTTPForbidden, HTTPNotFound, HTTPSeeOther
from pyramid.response import Response
from pyramid.security import effective_principals
from pyramid.view import view_config
from sqlalchemy.orm.exc import NoResultFound
import wtforms

from floof import model
from floof.forms import FloofForm, KeygenField
from floof.lib.authn import get_ca
from floof.lib.helpers import friendly_serial

log = logging.getLogger(__name__)


def get_cert(serial, user=None, check_validity=False):
    """Helper for fetching certs and running common authorization checks."""
    # XXX return a tuple or check result with isinstance()?
    try:
        cert = model.session.query(model.Certificate) \
                .filter_by(serial=serial) \
                .one()
    except NoResultFound:
        raise HTTPNotFound(detail="Certificate not found.")

    if cert is None:
        raise HTTPNotFound(detail="Certificate not found.")
    if user and cert not in user.certificates:
        raise HTTPForbidden(detail="That does not appear to be your certificate.")
    if check_validity and not cert.valid:
        raise HTTPNotFound(detail="That certificate has already expired or "
                "been revoked.")

    return cert


class CertificateForm(FloofForm):
    days = wtforms.fields.SelectField(u'Validity Period',
            coerce=int,
            choices=[(31, '31 days'), (366, '1 year'), (1096, '3 years')]
            )

class BrowserCertificateForm(CertificateForm):
    pubkey = KeygenField(u'Public Key')