package com.conveyal.taui.controllers;

import com.conveyal.taui.models.AddTripPattern;
import com.conveyal.taui.models.Modification;
import com.conveyal.taui.models.Project;
import com.conveyal.taui.models.Region;
import com.conveyal.taui.persistence.Persistence;
import com.conveyal.taui.util.JsonUtil;
import com.mongodb.QueryBuilder;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import spark.Request;
import spark.Response;

import java.util.Collection;

import static spark.Spark.get;

/**
 * Created by evan siroky on 5/3/18.
 */
public class TimetableController {
    private static final Logger LOG = LoggerFactory.getLogger(TimetableController.class);

    public static String getTimetables (Request req, Response res) {
        JSONArray json = new JSONArray();
        Collection<Region> regions = Persistence.regions.findAllForRequest(req);

        for (Region region : regions) {
            JSONObject r = new JSONObject();
            r.put("_id", region._id);
            r.put("name", region.name);
            JSONArray regionProjects = new JSONArray();
            for (Project project : region.getProjects()) {
                JSONObject p = new JSONObject();
                p.put("_id", project._id);
                p.put("name", project.name);
                JSONArray projectModifications = new JSONArray();
                Collection<Modification> modifications = Persistence.modifications.findPermitted(
                    QueryBuilder.start("projectId").is(project._id).and("type").is("add-trip-pattern").get(),
                    req.attribute("accessGroup")
                );
                for (Modification modification : modifications) {
                    AddTripPattern tripPattern = (AddTripPattern) modification;
                    JSONObject m = new JSONObject();
                    m.put("_id", modification._id);
                    m.put("name", modification.name);
                    JSONArray modificationTimetables = new JSONArray();
                    for (AddTripPattern.Timetable timetable : tripPattern.timetables) {
                        modificationTimetables.add(JsonUtil.objectMapper.valueToTree(timetable));
                    }
                    m.put("timetables", modificationTimetables);
                    projectModifications.add(m);
                }
                p.put("modifications", projectModifications);
                regionProjects.add(p);
            }
            r.put("projects", regionProjects);
            json.add(r);
        }

        return json.toString();
    }

    public static void register () {
        get("/api/timetables", TimetableController::getTimetables);
    }
}

@@ -1983,32 +1983,93 @@
 fication.name);%0A
+                    m.put(%22segments%22, tripPattern.segments);%0A
                 

Add modification segments to timetable endpoint