import rfc3161
import os.path

from django.utils import simplejson

__certificate_path = os.path.join(os.path.dirname(__file__), 'certum_certificate.crt')

__timestamper = rfc3161.RemoteTimestamper('http://time.certum.pl',
        certificate=open(__certificate_path).read())

class TimestampingError(RuntimeError):
    pass

def timestamp(content):
    try:
        return __timestamper(data=content)
    except Exception, e:
        raise TimestampingError(e)

def timestamp_json(json_dict):
    s = simplejson.dumps(json_dict)
    if s[-1] != '}':
        raise ValueError("timestamp_json takes a dictionnary as argument: %s" % s)
    tst, error = timestamp(s)
    if tst:
        return s[:-1] + ',"timestamp": "%s"}' % tst.encode('base64').strip()
    else:
        raise TimestampingError(error)

def check_timestamp_json(content, certificate):
    content, tst = content.rsplit(',"timestamp": "', 1)
    content += '}'
    tst = tst[:-2].decode('base64')
    return rfc3161.check_timestamp(tst, certificate, data=content)

