package seedu.tache.ui;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.logging.Logger;

import com.google.common.eventbus.Subscribe;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.concurrent.Worker;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import seedu.tache.commons.core.LogsCenter;
import seedu.tache.commons.events.model.TaskManagerChangedEvent;
import seedu.tache.commons.util.FxViewUtil;
import seedu.tache.model.task.DateTime;
import seedu.tache.model.task.ReadOnlyTask;

/**
 * The Calendar Panel of the App.
 */
public class CalendarPanel extends UiPart<Region> {
    private final Logger logger = LogsCenter.getLogger(CalendarPanel.class);
    private static final String FXML = "CalendarPanel.fxml";

    @FXML
    private WebView calendar;

    /**
     * @param placeholder The AnchorPane where the CalendarPanel must be inserted
     */
    public CalendarPanel(AnchorPane placeholder, ObservableList<ReadOnlyTask> taskList) {
        super(FXML);
        placeholder.setOnKeyPressed(Event::consume); // To prevent triggering events for typing inside the
                                                     // loaded Web page.
        FxViewUtil.applyAnchorBoundaryParameters(calendar, 0.0, 0.0, 0.0, 0.0);
        placeholder.getChildren().add(calendar);
        registerAsAnEventHandler(this);
        loadCalendar(taskList);
    }

    //@@author A0139925U
    private void loadCalendar(ObservableList<ReadOnlyTask> taskList) {
        try {
            String calendarTemplate = new String(Files.readAllBytes(Paths.get(System.getProperty("user.dir")
                    + "/src/main/resources/html/calendar.html")));
            WebEngine engine = calendar.getEngine();
            engine.loadContent(calendarTemplate);
            for (ReadOnlyTask task : taskList) {
                if (!task.getStartDateTime().isPresent()) {
                    continue;
                }
                engine.getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
                        @Override
                        public void changed(ObservableValue<? extends Worker.State> observable,
                                                Worker.State oldValue, Worker.State newValue) {
                            if (newValue != Worker.State.SUCCEEDED) {
                                return;
                            }
                            engine.executeScript(getLoadTaskExecuteScript(task));
                        }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //@@author A0142255M
    private String getLoadTaskExecuteScript(ReadOnlyTask task) {
        String title = task.getName().toString();
        String start = task.getStartDateTime().get().getDateTimeForFullCalendar();
        String end = "0"; // invalid format of datetime
        Optional<DateTime> endDateTime = task.getEndDateTime();
        if (task.getEndDateTime().isPresent()) {
            end = endDateTime.get().getDateTimeForFullCalendar();
        }
        String isActive = String.valueOf(task.getActiveStatus());
        return "add_event('" + title + "', '" + start + "', '" + end + "', '" + isActive + "')";

    }

    @Subscribe
    public void handleTaskManagerChangedEvent(TaskManagerChangedEvent event) {
        ObservableList<ReadOnlyTask> taskList = event.data.getTaskList();
        WebEngine engine = calendar.getEngine();
        engine.getLoadWorker().stateProperty().addListener((obs, oldState, newState) -> {
            if (newState == Worker.State.SUCCEEDED) {
                calendar.getEngine().executeScript("'remove_all'");
            }
        });
        loadCalendar(taskList);
    }
    //@@author

    /**
     * Frees resources allocated to the calendar.
     */
    public void freeResources() {
        calendar = null;
    }

}

@@ -22,92 +22,8 @@
 i;%0A%0A
-import java.io.IOException;%0Aimport java.nio.file.Files;%0Aimport java.nio.file.Paths;%0A
 impo
@@ -129,93 +129,8 @@
 e;%0A%0A
-import javafx.beans.value.ChangeListener;%0Aimport javafx.beans.value.ObservableValue;%0A
 impo
@@ -394,16 +394,44 @@
 ebView;%0A
+import seedu.tache.MainApp;%0A
 import s
@@ -1553,14 +1553,14 @@
  A01
-39925U
+42255M
 %0A   
@@ -1639,165 +1639,56 @@
     
-try %7B%0A            String calendarTemplate = new String(Files.readAllBytes(Paths.get(System.getProperty(%22user.dir%22)%0A                    + %22/src/main/r
+String calendarURL = MainApp.class.getR
 esource
-s
+(%22
 /htm
@@ -1704,24 +1704,35 @@
 r.html%22)
-));%0A    
+.toExternalForm();%0A
         
@@ -1776,28 +1776,24 @@
 ();%0A        
-  
-  
 engine.loadC
@@ -1795,15 +1795,8 @@
 load
-Content
 (cal
@@ -1804,23 +1804,14 @@
 ndar
-Template);%0A    
+URL);%0A
     
@@ -1859,28 +1859,24 @@
             
-  
-  
 if (!task.ge
@@ -1923,20 +1923,16 @@
         
-    
 continue
@@ -1949,734 +1949,92 @@
     
-    %7D%0A                engine.getLoadWorker().stateProperty().addListener(new ChangeListener%3CWorker.State%3E() %7B%0A                        @Override%0A                        public void changed(ObservableValue%3C? extends Worker.State%3E observable,%0A                                                Worker.State oldValue, Worker.State newValue) %7B%0A                            if (newValue != Worker.State.SUCCEEDED) %7B%0A                                return;%0A                            %7D%0A                            engine.executeScript(getLoadTaskExecuteScript(task));%0A                        %7D%0A                %7D);%0A            %7D%0A        %7D catch (IOException e) %7B%0A            e.printStackTrace();%0A        %7D%0A    %7D%0A%0A    //@@author A0142255M
+%7D%0A            engine.executeScript(getLoadTaskExecuteScript(task));%0A        %7D%0A    %7D%0A
 %0A   

Change html file retrieval for loading in jar file