import sys
import os

import requests
import datetime
import arrow
from django.utils import timezone

from django.core.management.base import BaseCommand
from rowers.models import Rower,Workout
import re
from django.db.models import Q
from rowers.dataprep import join_workouts

def name_short(name):
    expr = '(.*)\s.*\(\d+\)'
    match = re.findall(expr,name)

    if match:
        return match[0]

    return name

def get_duplicates(a):
    seen = {}
    dupes = []

    for x in a:
        if x not in seen:
            seen[x] = 1
        else:
            if seen[x] == 1:
                dupes.append(x)
            seen[x] += 1

    return seen


class Command(BaseCommand):
    def handle(self, *args, **options):
        rs = (r for r  in Rower.objects.all() if r.ispaid and r.autojoin)
        now = timezone.now()

        for r in rs:
            workouts = Workout.objects.filter(user=r,
                                              duplicate=False,
                                              startdatetime__gte=timezone.now()-datetime.timedelta(days=2))


            duplicates = get_duplicates(name_short(w.name) for w in workouts)

            for name, count in duplicates.items():
                if count > 1:
                    workouts2 = workouts.filter(
                        Q(name__contains=name)
                        )

                    duplicates2 = get_duplicates(w.date for w in workouts)
                    for dd, count in duplicates2.items():
                        if count > 1:
                            workouts3 = workouts2.filter(date=dd)
                            ids = [w.id for w in workouts3]
                            id, message = join_workouts(r,ids,title=name,
                                                        parent=workouts3[0],
                                                        killparents=True)
