# Copyright 2012 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.


"""
The Notifications module allows you to configure Jenkins to notify
other applications about various build phases.  It requires the
Jenkins notification plugin.

**Component**: notifications
  :Macro: notification
  :Entry Point: jenkins_jobs.notifications

"""

import xml.etree.ElementTree as XML

import jenkins_jobs.modules.base
import jenkins_jobs.modules.helpers as helpers


def http_endpoint(registry, xml_parent, data):
    """yaml: http
    Defines an HTTP notification endpoint.

    Requires the Jenkins :jenkins-plugins:`Notification Plugin
    <notification>`.

    :arg str format: notification payload format, JSON (default) or XML
    :arg str event: job events that trigger notifications: started,
        completed, finalized or all (default)
    :arg str url: URL of the endpoint
    :arg int timeout: Timeout in milliseconds for sending notification
        request (30 seconds by default)
    :arg int retries: Nr of times to retry sending notification in case
        sending notification fails. (0 by default)
    :arg int log: Number lines of log messages to send (0 by default).
        Use -1 for all (use with caution).

    Example:

    .. literalinclude:: \
    /../../tests/notifications/fixtures/http-endpoint002.yaml
       :language: yaml

    """
    endpoint_element = XML.SubElement(
        xml_parent, "com.tikal.hudson.plugins.notification." "Endpoint"
    )
    supported_formats = ["JSON", "XML"]
    supported_events = ["started", "completed", "finalized", "all"]
    fmt = data.get("format", "JSON").upper()
    event = data.get("event", "all").lower()
    branch = data.get("branch", ".*")
    mapping = [
        ("", "format", fmt, supported_formats),
        ("", "protocol", "HTTP"),
        ("", "event", event, supported_events),
        ("timeout", "timeout", 30000),
        ("retries", "retries", 0),
        ("log", "loglines", 0),
        ("buildNotes", "buildNotes", ""),
        ("branch", "branch", branch),
    ]
    helpers.convert_mapping_to_xml(endpoint_element, data, mapping, fail_required=True)

    # Add nested <urlInfo> block
    url_info = XML.SubElement(endpoint_element, "urlInfo")
    XML.SubElement(url_info, "urlOrId").text = data["url"]
    XML.SubElement(url_info, "urlType").text = data.get("url-type", "PUBLIC")


class Notifications(jenkins_jobs.modules.base.Base):
    sequence = 22

    component_type = "notification"
    component_list_type = "notifications"

    def gen_xml(self, xml_parent, data):
        properties = xml_parent.find("properties")
        if properties is None:
            properties = XML.SubElement(xml_parent, "properties")

        notifications = data.get("notifications", [])
        if notifications:
            notify_element = XML.SubElement(
                properties,
                "com.tikal.hudson.plugins."
                "notification."
                "HudsonNotificationProperty",
            )
            endpoints_element = XML.SubElement(notify_element, "endpoints")

            self.dispatch_component_list(
                "notification", notifications, endpoints_element
            )
