import os, sys
from datetime import datetime
from dateutil import relativedelta

import django
sys.path.append('../../../')
os.environ['DJANGO_SETTINGS_MODULE'] = 'ds_events.settings'
django.setup()

from time import sleep
from pprint import pprint as ppr
import pytz

from events.models import Organization, Scraper
import events.digitools as digitools

venue, created = Organization.objects.get_or_create(
     name="Cabooze",
     city="Minneapolis",
     website="https://www.cabooze.com/#/events",
     is_venue=True
    )

scraper,item_count_start = digitools.getScraper(venue)

event_type = ""

# Time Signatures
tz = pytz.timezone("US/Central")
DATETIME_FORMAT = '%b %d %I:%M %p %Y'
DATETIME_FORMAT_2 = '%A, %B %d @ %I%p %Y'

def get_events(ps, event_type):
    print("Getting events ...")
    contents = ps.xpath('.//*/div[@class="vp-event-row vp-widget-reset vp-venue-thecabooze"]')
    ppr(contents)
    for c in contents:
        try:
            event = {}
            date = c.xpath('.//*/span[@class="vp-month-n-day"]/text()')[0]
            print(date)
            month = date.split(" ")[0]
            time = c.xpath('.//*/span[@class="vp-time"]/text()')[0]
            year = datetime.now().year
            if month == "Jan":
                year = int(year) + 1
            event['calendar'] = scraper.calendar
            event['title'] = c.xpath('.//*/div[@class="vp-event-name"]/text()')[0]
            event['date'] = [date, time, str(year)]
            event['date'] = " ".join(event['date'])
            event['dateStamp'] = datetime.strptime(event['date'], DATETIME_FORMAT)
            event['link'] = "https://www.cabooze.com/" + c.xpath('.//a[@class="vp-event-link"]/@href')[0]
            print("Event Dict Created")
            ppr(event)
            digitools.createBasicEvent(event, event_type, venue)
            scraper.items+=1
        except Exception as e:
            print(e)
            ppr(event)
            print("\n\n+++\n\n")

if len(sys.argv) >= 2:
    arg1 = sys.argv[1]
    br = digitools.getBrowser(arg1)
else:
    print("No run_env")
    quit()

ps = digitools.getSource(br, venue.website)
get_events(ps, "Mu")
sleep(3)

digitools.updateScraper(scraper, item_count_start)
br.close()