
from __future__ import absolute_import
from __future__ import division

from vdsm.common import cmdutils
from vdsm.common import commands
from vdsm.gluster import exception as ge

from . import gluster_mgmt_api


_glusterEventsApi = cmdutils.CommandPath("gluster-eventsapi",
                                         "/sbin/gluster-eventsapi",
                                         "/usr/sbin/gluster-eventsapi",)


@gluster_mgmt_api
def webhookAdd(url, bearerToken=None):
    command = [_glusterEventsApi.cmd, "webhook-add", url]
    if bearerToken:
        command.append('--bearer_token=%s' % bearerToken)
    rc, out, err = commands.execCmd(command)
    if rc:
        raise ge.GlusterWebhookAddException(rc, out, err)
    else:
        return True


@gluster_mgmt_api
def webhookUpdate(url, bearerToken=None):
    command = [_glusterEventsApi.cmd, "webhook-mod", url]
    if bearerToken:
        command.append('--bearer_token=%s' % bearerToken)
    rc, out, err = commands.execCmd(command)
    if rc:
        raise ge.GlusterWebhookUpdateException(rc, out, err)
    else:
        return True


@gluster_mgmt_api
def webhookSync():
    command = [_glusterEventsApi.cmd, "sync"]
    rc, out, err = commands.execCmd(command)
    if rc:
        raise ge.GlusterWebhookSyncException(rc, out, err)
    else:
        return True


@gluster_mgmt_api
def webhookDelete(url):
    command = [_glusterEventsApi.cmd, "webhook-del", url]
    rc, out, err = commands.execCmd(command)
    if rc:
        raise ge.GlusterWebhookDeleteException(rc, out, err)
    else:
        return True
