from app import app
from datetime import datetime, timedelta, timezone
import os
import caldav
import datetime
from icalendar import cal, Event
from flask import render_template
from .models import Event
import requests
caldav_url = os.getenv('caldav_url')
username = os.getenv('username')
password = os.getenv('password')
cal_id = os.getenv('cal_id')


def daterange(start_date, end_date):
    for n in range(int((end_date - start_date).days)):
        yield datetime.datetime.date(start_date + timedelta(n))

@app.route('/')
def dashboard():
    today = datetime.datetime.now(tz=datetime.datetime.now(timezone.utc).astimezone().tzinfo)
    # today = datetime.datetime(2022,5,30, tzinfo=datetime.datetime.now(timezone.utc).astimezone().tzinfo)
    start_of_week = today - timedelta(days=today.weekday())   # Monday
    end_of_week = start_of_week + timedelta(days=7)  # Sunday

    events = []

    for url in [
        'https://www.calendarlabs.com/ical-calendar/ics/76/US_Holidays.ics',
    ]:
        r = requests.get(url)
        c = cal.Calendar.from_ical(r.content)

        events += Event.fromIcalendar(c)

    with caldav.DAVClient(url=caldav_url, username=username, password=password) as client:
        my_principal = client.principal()

        calendars = my_principal.calendars()
        for id in [cal_id]:
            calendar = my_principal.calendar(cal_id=id)
            events += Event.fromCalDavEvents(calendar.date_search(
            start=start_of_week, end=end_of_week, expand=False))

    for url in [
        'http://ical-cdn.teamsnap.com/team_schedule/5f1ddc9e-15b0-4912-84a2-11cc70e9e375.ics'
    ]:
        r = requests.get(url)
        c = cal.Calendar.from_ical(r.content)

        events += Event.fromIcalendar(c)

    days = []
    for single_date in daterange(start_of_week, end_of_week):
        days_events = [e for e in events if (e.dtstart.date() <= single_date <= e.dtend.date())]
        days.append((single_date, days_events))


    # breakpoint()
    pass
    # r = "<br>".join([event.vobject_instance.vevent.summary.value for event in events_fetched if event.vobject_instance.vevent.dtstart.value < datetime.now()])
    return render_template("dashboard.html",
                           days=days,
                           today=today)

