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="Green Room",
     city="Minneapolis",
     website="https://www.greenroommn.com/events",
     is_venue = True
    )

scraper,item_count_start = digitools.getScraper(venue)

event_type = "Mu"

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

def get_events(ps, event_type):
    contents = ps.xpath('.//*/div[@class="vp-event-card vp-venue-greenroom vp-col"]')
    for c in contents:
        try:
            event = {}
            time = c.xpath('.//*/span[@class="vp-time"]/text()')[0].strip()
            date = c.xpath('.//*/span[@class="vp-date"]/text()')[0].strip()
            month = date.split(" ")[1]
            year = datetime.now().year
            # if month == "Jan":
            #     year = int(year) + 1
            event['scraper'] = scraper
            event['calendar'] = scraper.calendar
            event['title'] = c.xpath('.//*/div[@class="vp-event-name"]/text()')[0]
            event['datetime'] = date + " " + str(year) + " " + time
            event['dateStamp'] = datetime.strptime(event['datetime'], DATETIME_FORMAT)
            event['link'] = venue.website + c.xpath('.//a[@class="vp-event-link"]/@href')[0]
            digitools.createBasicEvent(event, event_type, venue)
            scraper.items+=1
        except Exception as e:
            print(e)
            ppr(event)
            print("\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, event_type)
sleep(3)

br.close()

digitools.updateScraper(scraper, item_count_start)