'Add a Tag to an Event
S3Method for interactive requests
- designed to be called as an afterTagAdded callback to tag-it.js'

@staticmethod
def event_add_tag(r, **attr):

    event_id = r.id
    if ((not event_id) or (len(r.args) < 3)):
        raise HTTP(405, current.ERROR.BAD_METHOD)
    tag = r.args[2]
    db = current.db
    s3db = current.s3db
    ttable = s3db.cms_tag
    ltable = s3db.event_tag
    exists = db((ttable.name == tag)).select(ttable.id, ttable.deleted, ttable.deleted_fk, limitby=(0, 1)).first()
    if exists:
        tag_id = exists.id
        if exists.deleted:
            if exists.deleted_fk:
                data = json.loads(exists.deleted_fk)
                data['deleted'] = False
            else:
                data = dict(deleted=False)
            db((ttable.id == tag_id)).update(**data)
    else:
        tag_id = ttable.insert(name=tag)
    query = ((ltable.tag_id == tag_id) & (ltable.event_id == event_id))
    exists = db(query).select(ltable.id, ltable.deleted, ltable.deleted_fk, limitby=(0, 1)).first()
    if exists:
        if exists.deleted:
            if exists.deleted_fk:
                data = json.loads(exists.deleted_fk)
                data['deleted'] = False
            else:
                data = dict(deleted=False)
            db((ltable.id == exists.id)).update(**data)
    else:
        ltable.insert(event_id=event_id, tag_id=tag_id)
    output = current.xml.json_message(True, 200, current.T('Tag    Added'))
    current.response.headers['Content-Type'] = 'application/json'
    return output
