import time
import csv


def read_definition(definition):
    """Function for reading valid rows from definition.csv.
    Seas, lakes and rivers are skipped as uninteresting.
    The file also contains some empty (or reserved) colours, which are skipped.

    Returns a list of interesting rows.

    Arguments:
    definition -- path to definition.csv
    """

    start = time.time()
    print("Reading definition.csv")

    provs = []

    # Stuff to skip
    seas_and_rivers = ["Gulf", "Sea", "SEA", "Golf", "Biscay", "Donegal", "Galway", "Coast", "Cabo", 
                       "Strait", "Cote", "Atlantic", "Faroya", "Hav", "bukten", "Occe", "Channel",
                       "Firth", "Lake", "Saimaa", "The ", "bank", "Manche", "Islas", "Ponant",
                       "Indus", "Ganges", "Brahmaputra", "Seine", "Loire", "Garonne", "Danube", 
                       "Iskender", "Western", "East", "Nile Delta", "Levant", "Elbe", "Rhine", 
                       "Vistula", "Kattegat", "Waddenzee", "Daugava", "Volga1", "Volga2", "Volga3", 
                       "Volga4", "Volga5", "Volga6", "Volga7", "Volga8", "Volga9", "Svir", "Neva", "Don1",
                       "Don2", "Don3", "Don4", "Desna", "Oka", "Lovat", "Volkhov", "Dniester", 
                       "Dnieper1", "Dnieper2", "Dnieper3", "Dnipro", "Dny", "Dne", "Pripyat", "Dwina", "Kallavesi", "Bodensee"]

    #Näsijärvi, Oulujärvi, Mälaren, Hjälmaren, Vättern, Vänern, Onega, Päijänne, some unnamed lake in Siberia, unnamed spots in the Indian Ocean.
    #The names contain unicode characters and I'm skipping them this way, because I'm lazy.
    skip_id = [943, 957, 959, 961, 962, 963, 997, 1018, 1293, 1305, 1412]

    csv.register_dialect('ckii', delimiter=';', quoting=csv.QUOTE_NONE)

    with open(definition, 'r') as f:
        reader = csv.reader(f, 'ckii')

        for row in reader:
            if len(row) > 3 and row[0] != '':
                try:
                    prov_id = int(row[0])
                    prov_name = row[4]
                    allow = True

                    for skip_name in seas_and_rivers:
                        if prov_id in skip_id or prov_name.find(skip_name) != -1:
                            allow = False
                            break
                    # Try to get rgb-colours from fields.
                    if allow:    
                        r = int(row[1])
                        g = int(row[2])
                        b = int(row[3])
                        provs.append(row)
                except ValueError:
                    pass

    delta = time.time() - start
    print ("Reading definition.csv took %.3f seconds" %delta)
    return provs