import math
import warnings


def set_vector_density(data, minDistance=0):
    """Utility function to change density of vector plots.

    Args:
        data (:class:`xarray.core.dataarray.DataArray`):
            Data array that contains the vector plot latitude/longitude data.
        minDistance (:class:`int`):
            Value in degrees that determines the distance between the vectors.
    Returns:
        ds (:class:`xarray.core.dataarray.DataArray`):
            Sliced version of the input data array.
    """

    if minDistance <= 0:
        raise Exception("minDistance cannot be negative or zero.")
    else:
        lat_every = 1
        lon_every = 1

        # Get distance between points in latitude (y axis)
        lat = data['lat']
        latdifference = (float)(lat[1] - lat[0])

        # Get distance between points in longitude (x axis)
        lon = data['lon']
        londifference = (float)(lon[1] - lon[0])

        # Get distance between points that are diagonally adjacent
        diagDifference = math.sqrt(latdifference**2 + londifference**2)

        # Initialize ds
        ds = data

        if diagDifference >= minDistance and latdifference >= minDistance and londifference >= minDistance:
            warnings.warn('Plot spacing is alrady greater or equal to ' +
                          (str)(minDistance))

        # While the difference between two vectors is smaller than minDistance, increment the value that
        # the data arrays will be sliced by
        while diagDifference < minDistance or latdifference < minDistance or londifference < minDistance:

            # Get distance between points in latitude (y axis)
            latdifference = (float)(lat[lat_every] - lat[0])

            # Get distance between points in longitude (x axis)
            londifference = (float)(lon[lon_every] - lon[0])

            # Get distance between points that are diagonally adjacent
            diagDifference = math.sqrt(latdifference**2 + londifference**2)

            lat_every += 1
            lon_every += 1

        # Slice data arrays
        ds = data.isel(lat=slice(None, None, lat_every),
                       lon=slice(None, None, lon_every))

        return ds