import csv


def write_field_coverage(quantiles, values, ele_start, ele_stop, azi_start,
                         azi_stop, threshold, nvalid_min, datatype, timeinfo,
                         fname):
    """
    writes the quantiles of the coverage on a particular sector

    Parameters
    ----------
    quantiles : datetime array
        array containing the quantiles computed
    values : float array
        quantile value
    ele_start, ele_stop, azi_start, azi_stop : float
        The limits of the sector
    threshold : float
        The minimum value to consider the data valid
    nvalid_min : int
        the minimum number of points to consider that there are values in a
        ray
    datatype : str
        data type and units
    timeinfo : datetime object
        the time stamp of the data
    fname : str
        name of the file where to write the data

    Returns
    -------
    fname : str
        the name of the file where data has written

    """
    with open(fname, 'w', newline='') as csvfile:
        csvfile.write('# Quantiles of the field coverage\n')
        csvfile.write('# Datatype (Unit) : '+datatype+'\n')
        csvfile.write('# Time : '+timeinfo.strftime('%Y-%m-%d %H:%M:%S')+'\n')
        csvfile.write('# Sector specification:\n')
        csvfile.write('#   Azimuth start   : '+str(azi_start)+' deg\n')
        csvfile.write('#   Azimuth stop    : '+str(azi_stop)+' deg\n')
        csvfile.write('#   Elevation start : '+str(ele_start)+' deg\n')
        csvfile.write('#   Elevation stop  : '+str(ele_stop)+' deg\n')
        csvfile.write('# Threshold : '+str(threshold)+'\n')
        csvfile.write('# Minimum number of valid gates per ray : ' +
                      str(nvalid_min)+'\n')
        fieldnames = ['Quantile [%]', 'Rain extension [m]']
        writer = csv.DictWriter(csvfile, fieldnames)
        writer.writeheader()
        for i, quant in enumerate(quantiles):
            writer.writerow({
                'Quantile [%]': quant,
                'Rain extension [m]': values[i]})

        csvfile.close()

    return fname