package dynamic.future;

import com.google.api.services.calendar.model.Event;
import dynamic.future.events.GoogleCalendar;
import dynamic.future.events.IcalToEvent;
import dynamic.future.events.WebGrabber;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

public class EventsToCalendar {

    static String ic_url_stub = "http://www3.imperial.ac.uk";
    static String events_rss_feed = "http://www3.imperial.ac.uk/imperialnewsevents/eventsfront?pid=5591_177353454_5591_177343951_177343951";
    static String event_id_start = "/imperialnewsevents/eventical?p_eventid=";

    static String clientId = "325532296526.apps.googleusercontent.com";
    static String clientSecret = "_2Kht14yuveaU7Cpn7wDYiAd";
    static String calendarId = "ck7d1m1553asa611c6482o72po@group.calendar.google.com";
    static String appName = "DocEventsCalendar";

    public static void main(String[] args) throws IOException {

        ArrayList<URL> event_urls = getEventURLS();

        ArrayList<Event> events = new ArrayList<Event>();

        for (URL url : event_urls) {

            String webc = WebGrabber.getWebContents(url);

            int id_start = webc.indexOf(event_id_start);
            int id_end = webc.indexOf("\"", id_start);
            String ical_ref = webc.substring(id_start, id_end);

            URL ical_url = new URL(ic_url_stub + ical_ref);

            String ical = WebGrabber.getWebContents(ical_url);
            Event e = IcalToEvent.convertIcalToEvent(ical);
            e.setDescription(url.toString());
            events.add(e);

        }
        System.out.println("Retreived " + events.size() + "dynamic/future/events");

        GoogleCalendar.login(clientId, clientSecret, appName);
        GoogleCalendar.clearCalendar(calendarId);

        for (Event event : events) {
            GoogleCalendar.AddEvent(calendarId, event);
        }

        ArrayList<Event> event_list = GoogleCalendar.allEvents(calendarId);
        System.out.println("Added " + event_list.size() + "dynamic/future/events");

    }

    private static ArrayList<URL> getEventURLS() throws MalformedURLException {

        String webs = WebGrabber.getWebContents(new URL(events_rss_feed));

        ArrayList<URL> event_urls = new ArrayList<URL>();

        // split rss feed into multiple events
        int pos = 0;
        while ((pos = webs.indexOf("<entry", pos + 1)) >= 0) {

            int entry_close = webs.indexOf("</entry", pos);
            String entry = webs.substring(pos, entry_close);

            int url_start = entry.indexOf("<id>");
            int url_end = entry.indexOf("</id>");
            event_urls.add(new URL(entry.substring(url_start + 4, url_end)));
        }

        return event_urls;

    }


}
