Arguments: <document_id> <label_name> [<label_color>]

    Add a label on a document.

    Color must be specified if the label doesn't exist yet.
    Color will be ignored if the label already exists.
    Color format must be given in hexadecimal format. Ex: #abcdef

    Possible JSON replies:
        --
        { "status": "ok", "docid": "xxxxx", "label": "yyyyy" }
        --
        {
            "status": "error", "exception": "yyy",
            "reason": "xxxx", "args": "(xxxx, )"
        }

def cmd_add_label(docid, label_name, color=None):
    """
    Arguments: <document_id> <label_name> [<label_color>]

    Add a label on a document.

    Color must be specified if the label doesn't exist yet.
    Color will be ignored if the label already exists.
    Color format must be given in hexadecimal format. Ex: #abcdef

    Possible JSON replies:
        --
        { "status": "ok", "docid": "xxxxx", "label": "yyyyy" }
        --
        {
            "status": "error", "exception": "yyy",
            "reason": "xxxx", "args": "(xxxx, )"
        }
    """
    dsearch = get_docsearch()
    doc = dsearch.get(docid)
    if doc is None:
        raise Exception(
            "Document {} not found. Cannot add label on it".format(
                docid
            )
        )

    label = None
    for clabel in dsearch.label_list:
        if clabel.name == label_name:
            label = clabel
            break
    if not label and not color:
        raise Exception(
            "Label {} doesn't exist yet, and no color has been provided".format(
                label_name
            )
        )
    if not label:
        label = Label(label_name, color)
        dsearch.create_label(label)

    dsearch.add_label(doc, label)
    verbose("Label {} added on document {}".format(
        label_name, docid
    ))
    reply({
        "docid": docid,
        "label": label_name,
    })