// Souffle - A Datalog Compiler
// Copyright (c) 2017, The Souffle Developers. All rights reserved
// Licensed under the Universal Permissive License v 1.0 as shown at:
// - https://opensource.org/licenses/UPL
// - <souffle root>/licenses/SOUFFLE-UPL.txt

.type Airport <: symbol
.type Hour <: number
.type Route = [
	source : Airport,
	destination : Airport,
	start : Hour,
	duration : Hour
]

// List of flights
.decl flight(r : Route)
flight(["Sydney", "Melbourne", 8, 2]).
flight(["Sydney", "Melbourne", 20, 2]).
flight(["Sydney", "Singapore", 6, 10]).
flight(["Melbourne", "Auckland", 14, 4]).
flight(["Sydney", "Auckland", 12, 3]).
flight(["Singapore", "Tokyo", 21, 12]).
flight(["Singapore", "Dubai", 10, 11]).
flight(["Singapore", "London", 14, 14]).
flight(["Dubai", "London", 5, 6]).
flight(["London", "New York", 17, 15]).
flight(["London", "New York", 5, 15]).
flight(["London", "Oslo", 15, 3]).
flight(["London", "Paris", 10, 3]).
flight(["London", "Reykjavik", 8, 5]).
flight(["Oslo", "Reykjavik", 9, 4]).
flight(["Oslo", "Reykjavik", 21, 4]).
flight(["Los Angeles", "New York", 14, 5]).
flight(["Tokyo", "Los Angeles", 4, 14]).
flight(["Singapore", "Los Angeles", 9, 14]).
flight(["Singapore", "Los Angeles", 17, 14]).
flight(["Tokyo", "Vancouver", 12, 10]).
flight(["Singapore", "Vancouver", 18, 14]).
flight(["Los Angeles", "Vancouver", 5, 5]).

// Input starting airport and time
.decl travel(s : Airport, t : Hour)
.input travel()

// Find all connecting flights from starting airport
.decl connection(s : Airport, d : Airport, t : Hour, h : Hour)
.output connection()
connection(s, d, (t + h) % 24, (24 + t - tx) % 24 + h) :- travel(s, tx), flight([s, d, t, h]).
connection(s, d, (tx + h) % 24, hx + (24 + t - tx) % 24 + h) :- connection(s, x, tx, hx), flight([x, d, t, h]).

// Total time in hours to reach destination airport
.decl total_time(d : Airport, h : Hour)
.output total_time()
total_time(d, h) :- connection(s, d, _, _), h = min x : connection(s, d, _, x).
