import re
import sys, os

sys.path.append("/var/lib/django")
from django.core.management import setup_environ
from pbp_com import settings

setup_environ(settings)
import re
import urllib
import urllib2
import time
from datetime import datetime, timedelta
import dateutil
from almanac.models import Day, AstroChart, TideChart, TideDay, Tide
from directory.models import Place
from BeautifulSoup import BeautifulStoneSoup

### SET YOUR TIDE FILE NAME HERE ###
tides = BeautifulStoneSoup(open("bar_harbor_2014.xml"))
### SET THE YEAR YOUR ARE UPLOADING HERE ###
year = "2014"
place = Place.objects.get(slug="bar-harbor-public-wharf")


def fix_time(str, today, chart):
    """if chart.dst_start < today.date < chart.dst_end:
        delta=timedelta(hours=1)
    else:
        delta=timedelta(hours=0)"""
    return time.strftime(
        "%H:%M", datetime(*time.strptime(str, "%I:%M %p")[0:5]).timetuple()
    )


""" End of fix_time() """


tide_table = []

try:
    chart = TideChart.objects.get(year__exact=year, place__exact=place)
except TideChart.DoesNotExist:
    raise Exception(
        "Currently you have to manually add a tide chart to hold this info before in can be imported."
    )

try:
    astro_chart = AstroChart.objects.get(year__exact=year)
except AstroChart.DoesNotExist:
    raise Exception(
        "You must create an astronomical chart for the year you wish to input tide data for."
    )

days = Day.objects.filter(date__year=chart.year)
for day in days:
    print "Processing %s" % day.date
    days_tides = tides.findAll(text=re.sub("-", "/", str(day.date)))
    print days_tides
    try:
        tide_1 = days_tides[0].parent.parent
    except:
        pass
    tide_2 = days_tides[1].parent.parent
    tide_3 = days_tides[2].parent.parent
    try:
        tide_4 = days_tides[3].parent.parent
    except:
        pass
    tideday = TideDay.objects.create(day=day, tide_chart=chart)
    if tide_1:
        tideday.tide_1 = Tide.objects.create(
            time=fix_time(tide_1.time.contents[0], datetime.today(), astro_chart),
            level=tide_1.predictions_in_ft.contents[0],
            state=tide_1.highlow.contents[0],
        )
    tideday.tide_2 = Tide.objects.create(
        time=fix_time(tide_2.time.contents[0], datetime.today(), astro_chart),
        level=tide_2.predictions_in_ft.contents[0],
        state=tide_2.highlow.contents[0],
    )
    tideday.tide_3 = Tide.objects.create(
        time=fix_time(tide_3.time.contents[0], datetime.today(), astro_chart),
        level=tide_3.predictions_in_ft.contents[0],
        state=tide_3.highlow.contents[0],
    )
    if tide_4:
        tideday.tide_4 = Tide.objects.create(
            time=fix_time(tide_4.time.contents[0], datetime.today(), astro_chart),
            level=tide_4.predictions_in_ft.contents[0],
            state=tide_4.highlow.contents[0],
        )
    tideday.save()
