"""
.. module:: nws_cap
.. moduleauthor:: Phil Fenstermacher <phillip.fenstermacher@gmail.com>

"""

class CAP_Alert:
    """A class to read information out of an NWS Public Alert in CAP form
    Instances are usually created by NWS_CAP.CAP_Feed.
    """

    def __init__(self, cap_alert, nsmap):
        """
        Instantiate a CAP_Alert object.

        Args:
            cap_alert (lxml.objectify.): An lxml object of the alert
            nsmap (dict): The namespace map for the alert (generated by lxml)
        """
        self.alert = cap_alert
        self.nsmap = nsmap

    def get_field(self, name):
        """
        Get the value of a particular alert field

        Args:
            name (str): The name of the element you want to return the value of

        Returns:
            A string containing the value of name
        """
        if not ':' in name:
            return self.alert[name]
        else:
            parts = name.split(':')
            return str(self.alert['{' + self.nsmap[parts[0]] + '}' + parts[1]])

    def get_geocode(self, notation='UGC'):
        """
        Get a list of locations geocoded in the alert

        Kwargs:
            notation (str): The type of geocodes you want to use (UGC (default) or FIPS6)

        Returns:
            list: A list of areas covered by the alert

        .. note::
            UGC is the same as zone identifiers
        """
        locations = self.alert['{' + self.nsmap['cap'] + '}geocode']
        for n, v in zip(
                locations.iterchildren(tag='{' + self.nsmap[None] + '}valueName'),
                locations.iterchildren(tag='{' + self.nsmap[None] + '}value')):
            if n == notation:
                return v.text.split(' ')

    def get_polygon(self):
        """
        Return a list of coordinates that make up the vertices of the alert polygon

        Returns:
            list: A list of lists containing the lat/long coordinates
        """
        corners = list()
        polygon = self.alert['{' + self.nsmap['cap'] + '}polygon']
        for pair in polygon.text.split(' '):
            coords = pair.split(',')
            corners.append([coords[0], coords[1]])
        return corners

    def __str__(self):
        """
        Output the alert in string form.

        Returns:
            string: The title of the alert
        """
        return self.get_field('title')

