from django.core.management import BaseCommand
from participant.models import Participant
from survey.api import ObservationApi
from dateutil.parser import parse
from datetime import datetime
import pytz

__author__ = 'nick'

class Command(BaseCommand):

    def handle(self, *args, **kwargs):
    
        participants = Participant.objects.raw("""
            SELECT id,timezone, a.Name AS mysql_timezone FROM participant_participant p 
            LEFT JOIN (
                SELECT `Name` FROM mysql.time_zone_name
            ) AS a ON a.Name = timezone""")
        for participant in participants:
            if participant.mysql_timezone == None:
                observation = ObservationApi()._filter(participant=participant.id).filter(date_value__isnull=False).first()
                try:
                    date = parse(observation.date_value)
                except Exception as e:
                    print e
                    pass
                seconds = (24-(date.tzinfo._offset.seconds / 3600))*60
                zone = False
                for tz in map(pytz.timezone, pytz.all_timezones_set):
                    tzinfos = getattr(tz, '_tzinfos', [(None, None, None)])
                    for tzinfo in tzinfos:
                        if tzinfo[0] != None:
                            if ((24-(tzinfo[0].seconds / 3600))*60) == seconds:
                                zone = tzinfos[tzinfo]
                                break
                    if zone:
                        break
                participant.timezone = zone
                participant.save()