import csv


def write_colocated_gates(coloc_gates, fname):
    """
    Writes the position of gates colocated with two radars

    Parameters
    ----------
    coloc_gates : dict
        dictionary containing the colocated gates parameters
    fname : str
        file name where to store the data

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

    """
    with open(fname, 'w', newline='') as csvfile:
        csvfile.write('# Colocated radar gates data file\n')
        csvfile.write('# Comment lines are preceded by "#"\n')
        csvfile.write('#\n')

        fieldnames = [
            'rad1_ray_ind', 'rad1_rng_ind', 'rad1_ele', 'rad1_azi', 'rad1_rng',
            'rad2_ray_ind', 'rad2_rng_ind', 'rad2_ele', 'rad2_azi', 'rad2_rng']
        writer = csv.DictWriter(csvfile, fieldnames)
        writer.writeheader()
        for i, rad1_ray_ind in enumerate(coloc_gates['rad1_ray_ind']):
            writer.writerow({
                'rad1_ray_ind': rad1_ray_ind,
                'rad1_rng_ind': coloc_gates['rad1_rng_ind'][i],
                'rad1_ele': coloc_gates['rad1_ele'][i],
                'rad1_azi': coloc_gates['rad1_azi'][i],
                'rad1_rng': coloc_gates['rad1_rng'][i],
                'rad2_ray_ind': coloc_gates['rad2_ray_ind'][i],
                'rad2_rng_ind': coloc_gates['rad2_rng_ind'][i],
                'rad2_ele': coloc_gates['rad2_ele'][i],
                'rad2_azi': coloc_gates['rad2_azi'][i],
                'rad2_rng': coloc_gates['rad2_rng'][i]})

        csvfile.close()

    return fname