import db
import logging

from ckan.plugins.toolkit import get_validator, ValidationError
from ckan.lib.dictization import table_dictize
import ckan.lib.navl.dictization_functions as df

log = logging.getLogger(__name__)

schema = {
    'id': [get_validator('ignore_empty'), unicode],
    'address': [get_validator('not_empty'), unicode],
    'topic': [get_validator('not_empty'), unicode],
    'user_id': [get_validator('ignore_missing'), unicode],
    'created_at': [get_validator('ignore_missing'), get_validator('isodate')]
}

schema_get = {
    'id': [get_validator('not_empty'), unicode]
}

def webhook_create(context, data_dict):
    data, errors = df.validate(data_dict, schema, context)

    if errors:
        raise ValidationError(errors)

    webhook = db.Webhook()
    webhook.address = data['address']
    webhook.topic = data['topic']
    webhook.save()

    session = context['session']
    session.add(webhook)
    session.commit()

    return webhook.id

def webhook_show(context, data_dict):
    data, errors = df.validate(data_dict, schema_get, context)
    if errors:
        raise ValidationError(errors)

    webhook = db.Webhook.get(id=data['id'])
    return table_dictize(webhook, context)

def webhook_delete(context, data_dict):
    pass

@@ -130,16 +130,48 @@
 dictize%0A
+from ckan.logic import NotFound%0A
 import c
@@ -1197,16 +1197,66 @@
 %5B'id'%5D)%0A
+    if webhook is None:%0A        raise NotFound()%0A%0A
     retu
@@ -1339,9 +1339,266 @@
     
-pass
+data, errors = df.validate(data_dict, schema_get, context)%0A    if errors:%0A        raise ValidationError(errors)%0A%0A    webhook = db.Webhook.get(id=data%5B'id'%5D)%0A    session = context%5B'session'%5D%0A    session.delete(webhook)%0A    session.commit()%0A%0A    return data%5B'id'%5D
 %0A

raise 404 if webhook id not found