import csv
from math import radians, cos, sin, asin, sqrt

import sys
reload(sys)
sys.setdefaultencoding("utf-8")

def haversine(lat1, lon1, lat2, lon2):
    """
    Calculate the great circle distance between two points 
    on the earth (specified in decimal degrees)
    """
    # convert decimal degrees to radians 
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
    # haversine formula 
    dlon = lon2 - lon1 
    dlat = lat2 - lat1 
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a)) 
    km = 6367 * c
    return km*1000

def distance(type1, type2, distance, year1, year2, rating):
    """
    Calculate the recommendation distance between two places
    """
    result = 0

    if type1 == type2:
        result = result+10

    if distance <= 500:
        result = result+30
    elif (distance > 500 and distance <= 1000):
        result = result+20
    elif (distance > 1000 and distance <= 2000):
        result = result+10

    if year1 == year2:
        result = result+30
    elif ((year2 - 1) == year1 or (year2 + 1) == year1):
        result = result+20
    elif ((year2 - 2) == year1 or (year2 + 2) == year1):
        result = result+10

    if (rating >= 4 and rating < 5):
        result = result+30
    elif (rating >= 3 and rating < 4):
        result = result+20
    elif (rating >= 2 and rating < 3):
        result = result+10

    return result;

print "Welcome to the Distance Calculator App!"

with open('distances.csv', 'wb') as ff:
    writer = csv.writer(ff, delimiter=";", quoting=csv.QUOTE_ALL)
    with open('result.csv', 'rb') as f:
        reader = csv.reader(f, delimiter=";", quoting=csv.QUOTE_NONE)
        rows = list(reader)

        for row1 in rows:
            for row2 in rows:
                lat1 = float(row1[2].replace('"', ''));
                lon1 = float(row1[3].replace('"', ''));
                lat2 = float(row2[2].replace('"', ''));
                lon2 = float(row2[3].replace('"', ''));
                year1 = int(row1[7].replace('"', ''));
                year2 = int(row2[7].replace('"', ''));
                rating = float(row2[8].replace('"', ''));
                lst = row1 + row2

                lst.append(str(distance(row1[6],row2[6],haversine(lat1, lon1, lat2, lon2),year1,year2,rating)))
                
                writer.writerow(lst)

print "END"