import csv
from django.core.management.base import BaseCommand
from person.models import Person, Link, LINK_TYPES, Role
from django.contrib.gis.geos import Point
from dms2dec.dms_convert import dms2dec
from datetime import datetime
from astropy.time import Time
import re

def dms_to_dd(d, m, s):
    dd = d + float(m)/60 + float(s)/3600

def split_text(s):
    split = s.lower().split(' ')
    final_list = []
    if "patron" in split and "of" in split and "science" in split and "education" in split:
        split.remove("patron")
        split.remove("of")
        split.remove("science")
        split.remove("education")
        final_list.append("Patron of Science Education")

    if "and" in split:
        split.remove("and")

    for word in split:
        final_list.append(word)

    return final_list

class Command(BaseCommand):
    help = 'Reads a CSV file and saves the data to the database'

    def add_arguments(self, parser):
        parser.add_argument('csv_file', type=str)

    def handle(self, *args, **options):
        csv_file = options['csv_file']
        link_type_list = [x[1] for x in LINK_TYPES]
        with open(csv_file) as f:
            reader = csv.DictReader(f)
            for row in reader:
                dms_latitude, dms_longitude = row['coordinate'].split()

                if "." in dms_latitude:
                    latitude = float(re.sub("[^0-9\.]", "", dms_latitude))
                    longitude = float(re.sub("[^0-9\.]", "", dms_longitude))
                    latitude_hemisphere = 'N' if 'N' in dms_latitude else 'S'
                    longitude_hemisphere = 'E' if 'E' in dms_longitude else 'W'
                    if latitude_hemisphere == 'S':
                        latitude = -latitude
                    if longitude_hemisphere == 'W':
                        longitude = -longitude
                else:
                    latitude = dms2dec(dms_latitude)
                    longitude = dms2dec(dms_longitude)


                location = Point(longitude, latitude)

                role_str = row['Role']
                row_roles = split_text(role_str)
                roles = []
                for role in row_roles:
                    role_obj, created = Role.objects.get_or_create(name=role.strip().title())
                    roles.append(role_obj)


                person = Person.objects.create(
                    name=row['Name'],
                    gender=row['Gender'],
                    locality=row['Locality'],
                    year=int(row['Date']),
                    coordinate=location,
                )
                person.roles.add(*roles)

                for link_type, link in row.items():
                    if (link_type in link_type_list) and link:
                        link_type = LINK_TYPES[link_type_list.index(link_type)][0]
                        # link_type = link_type.replace(' ', '_').upper()

                        Link.objects.create(
                            link=link,
                            type=link_type,
                            person=person
                        )