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, Calendar
import events.digitools as digitools

venue, created = Organization.objects.get_or_create(
     name="Amsterdam Bar & Hall",
     city="St. Paul",
     website="https://www.amsterdambarandhall.com/events-new/",
     is_venue=True
    )

scraper,item_count_start = digitools.getScraper(venue)

DATETIME_FORMAT = '%B %d  %Y %I:%M%p'
DATETIME_FORMAT_2 = '%A, %B %d @ %I%p %Y'

def get_events(ps):
    contents = ps.xpath('.//*/ul[@class="events-list"]/li')
    for c in contents:
        try:
            event = {}
            day = c.xpath('.//*/div[@class="date-day"]/text()')[0]
            month = c.xpath('.//*/div[@class="date-month"]/text()')[0]
            year = datetime.now().year
            event['scraper'] = scraper
            event['calendar'] = scraper.calendar
            event['title'] = c.xpath('.//div/h4/a/text()')[0]
            event['date'] = [month, day, str(year),  c.xpath('.//div[@class="event-info"]/p/text()')[0].split(" ")[0]]
            event['date']  = " ".join(event['date'])
            event['dateStamp'] =datetime.strptime(event['date'], DATETIME_FORMAT)
            event['link'] = c.xpath('.//div[@class="event-info"]/h4/a/@href')[0]
            if " presents" in event['title']:
                event['title'] = event['title'].split("presents")[1][1:].strip()
            if event['title'].startswith('.'):
                print("BLAHH\n")
                event['title'] = event['title'][1:].strip()
            digitools.createBasicEvent(event, "Mu", venue)
            scraper.items+=1
        except Exception as e:
            print(e)


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)
sleep(3)
br.close()

digitools.updateScraper(scraper, item_count_start)