from rowers.models import (
    StandardCollection,CourseStandard,
    VirtualRaceResult,IndoorVirtualRaceResult,
    )

import pandas as pd
import arrow
import datetime

def save_scoring(name,user,filename,id=0,notes=""):
    if id==0:
        collection = StandardCollection(name=name,manager=user,notes=notes)
        collection.save()
        standards = CourseStandard.objects.filter(standardcollection=collection)
        for standard in standards:
            standards.delete()

    else:
        try:
            collection = StandardCollection.objects.get(id=id)
            collection.name = name
            collection.notes = notes
            collection.save()
            standards = CourseStandard.objects.filter(standardcollection=collection)
            for standard in standards:
                records1 = VirtualRaceResult.objects.filter(entrycategory=standard)
                records2 = IndoorVirtualRaceResult.objects.filter(entrycategory=standard)
                if records1.count()+records2.count() == 0:
                    standard.delete()


        except StandardCollection.DoesNotExist:
            return 0

    try:
        df = pd.read_csv(filename)
    except:
        return 0

    df.rename(
        columns={
            'name':'Name',
            'agemax':'MaxAge',
            'agemin':'MinAge',
            'adaptiveclass':'AdaptiveClass',
            'coursedistance':'CourseDistance',
            'coursetime':'CourseStandard',
            'boatclass':'BoatClass',
            'boattype':'BoatType',
            'sex':'Gender',
            'weightclass':'WeightClass',
            'skillclass':'SkillClass',
            },
            inplace=True)

    df = df.drop_duplicates(['Name'])

    for index, row in df.iterrows():
        try:
            name = row['Name']
        except KeyError:
            continue

        try:
            coursedistance = row['CourseDistance']
            coursetime = row['CourseStandard']
            t = datetime.datetime.strptime(coursetime,'%M:%S.%f')
            delta = datetime.timedelta(hours=t.hour, minutes=t.minute, seconds=t.second,microseconds=t.microsecond)
            seconds = delta.total_seconds()

            referencespeed = coursedistance/seconds
        except KeyError:
            continue

        try:
            agemin = row['MinAge']
            agemax = row['MaxAge']
            agemin = int(agemin)
            agemax = int(agemax)
        except KeyError:
            agemin = 0
            agemax = 120

        try:
            boatclass = row['BoatClass']
            if boatclass.lower() in ['standard','olympic','normal','water']:
                boatclass = 'water'
            elif boatclass.lower() in ['erg','c2','concept','static','rower']:
                boatclass = 'rower'
            elif boatclass.lower() in ['dynamic']:
                boatclass = 'dynamic'
            elif boatclass.lower() in ['slides','slide','slider','sliders']:
                boatclass = 'slides'
            elif boatclass.lower() in ['c','c-boat']:
                boatclass = 'c-boat'
            elif boatclass.lower() in ['coastal','coast']:
                boatclass = 'coastal'
            elif boatclass.lower() in ['church','churchboat','finnish','finland']:
                boatclass = 'churchboat'
        except KeyError:
            boatclass = 'water'

        try:
            boattype = row['BoatType']
        except KeyError:
            boattype = '1x'

        try:
            sex = row['Gender']
            if sex.lower() in ['m','men','male','open']:
                sex = 'male'
            elif sex.lower() in ['mix','mixed']:
                sex = 'mixed'
            else:
                sex = 'female'
        except KeyError:
            sex = 'female'

        try:
            weightclass = row['WeightClass']
            if weightclass.lower() in ['hwt','h','o','heavy','open']:
                weightclass = 'hwt'
            elif weightclass.lower() in ['lwt','l','light','lights','lighties']:
                weightclass = 'lwt'
        except KeyError:
            weightclass = 'hwt'

        adaptiveclass = 'None'
        try:
            adaptiveclass = row['AdaptiveClass']
            if adaptiveclass.lower() in ['o','open','none','no']:
                adaptiveclass = 'None'
        except KeyError:
            adaptiveclass = 'None'

        try:
            skillclass = row['SkillClass']
        except KeyError:
            skillclass = 'Open'

        # finding existing standard
        existingstandards = CourseStandard.objects.filter(name=name,standardcollection=collection)
        #print(existingstandards,collection)
        if existingstandards:
            existingstandards.update(
                name=name,
                coursedistance=coursedistance,
                referencespeed=referencespeed,
                coursetime=coursetime,
                agemin=agemin,
                agemax=agemax,
                boatclass=boatclass,
                boattype=boattype,
                sex=sex,
                weightclass=weightclass,
                adaptiveclass=adaptiveclass,
                skillclass=skillclass,
                standardcollection = collection,
            )
        else:
            #print('not')
            standard = CourseStandard(
                name=name,
                coursedistance=coursedistance,
                referencespeed=referencespeed,
                coursetime=coursetime,
                agemin=agemin,
                agemax=agemax,
                boatclass=boatclass,
                boattype=boattype,
                sex=sex,
                weightclass=weightclass,
                adaptiveclass=adaptiveclass,
                skillclass=skillclass,
                standardcollection = collection,
                )

            standard.save()

    return collection.id
