#!/usr/bin/env python

from datetime import datetime, timedelta

from aman.config.RunwaySequencing import RunwayAssignmentType
from aman.sys.aco.Configuration import Configuration
from aman.sys.aco.Constraints import SpacingConstraints
from aman.sys.aco.Node import Node

class RunwayManager:
    def __init__(self, configuration : Configuration):
        self.Spacings = SpacingConstraints()
        self.Configuration = configuration

        # initialize the tracker which inbound arrives at which runway
        self.RunwayInbounds = {}
        if None != configuration.PreceedingInbounds:
            for runway in configuration.PreceedingInbounds:
                self.RunwayInbounds[runway] = configuration.PreceedingInbounds[runway]
        for runway in configuration.RunwayConstraints.ActiveArrivalRunways:
            if not runway.Runway.Name in self.RunwayInbounds:
                self.RunwayInbounds[runway.Runway.Name] = None

    def calculateEarliestArrivalTime(self, runway : str, node : Node, useETA : bool, earliestArrivalTime : datetime):
        constrainedETA = None

        if None != self.RunwayInbounds[runway]:
            # get the WTC based ETA
            if None == self.RunwayInbounds[runway].Inbound.WTC or None == node.Inbound.WTC:
                spacingWTC = 3
            else:
                spacingWTC = self.Spacings[self.RunwayInbounds[runway].Inbound.WTC][node.Inbound.WTC]

            # get the runway time spacing
            spacingRunway = self.Configuration.RunwayConstraints.findRunway(runway).Spacing
            constrainedETA = self.RunwayInbounds[runway].Inbound.PlannedArrivalTime + timedelta(minutes = max(spacingWTC, spacingRunway) / (node.Inbound.PerformanceData.SpeedApproach / 60))

        # calculate the arrival times for the dependent inbounds
        for dependentRunway in self.Configuration.RunwayConstraints.findDependentRunways(runway):
            if None != self.RunwayInbounds[dependentRunway.Runway.Name]:
                candidate = self.RunwayInbounds[dependentRunway.Runway.Name].Inbound.PlannedArrivalTime + timedelta(minutes = 3 / (node.Inbound.PerformanceData.SpeedApproach / 60))
                if None == constrainedETA or candidate > constrainedETA:
                    constrainedETA = candidate

        # get the arrival time on the runway of the inbound
        if True == useETA:
            arrivalTime = node.ArrivalCandidates[runway].EarliestArrivalTime
        else:
            arrivalTime = node.ArrivalCandidates[runway].InitialArrivalTime

        if None == constrainedETA:
            eta = max(arrivalTime, earliestArrivalTime)
        else:
            eta = max(constrainedETA, earliestArrivalTime)

        return eta, eta - arrivalTime

    def selectShallShouldMayArrivalRunway(self, node : Node, runways, useETA : bool, earliestArrivalTime : datetime):
        candidate = None
        delay = None

        for runway in runways:
            if True == useETA:
                reference = node.ArrivalCandidates[runway.Runway.Name].EarliestArrivalTime
            else:
                reference = node.ArrivalCandidates[runway.Runway.Name].InitialArrivalTime

            eta, _ = self.calculateEarliestArrivalTime(runway.Runway.Name, node, useETA, earliestArrivalTime)
            if None == delay:
                delay = eta - reference
                candidate = runway
            elif delay > (eta - reference):
                delay = eta- reference
                candidate = runway

        return candidate

    def executeShallShouldMayAssignment(self, node : Node, useETA : bool, earliestArrivalTime : datetime):
        shallRunways = []
        shouldRunways = []
        mayRunways = []

        for runway in self.Configuration.RunwayConstraints.ActiveArrivalRunways:
            # test the shall assignments
            if RunwayAssignmentType.AircraftType in runway.ShallAssignments:
                if node.Inbound.Report.aircraft.type in runway.ShallAssignments[RunwayAssignmentType.AircraftType]:
                    shallRunways.append(runway)
            if RunwayAssignmentType.GateAssignment in runway.ShallAssignments:
                if node.Inbound.Report.plannedGate in runway.ShallAssignments[RunwayAssignmentType.GateAssignment]:
                    shallRunways.append(runway)

            # test the should assignments
            if RunwayAssignmentType.AircraftType in runway.ShouldAssignments:
                if node.Inbound.Report.aircraft.type in runway.ShouldAssignments[RunwayAssignmentType.AircraftType]:
                    shouldRunways.append(runway)
            if RunwayAssignmentType.GateAssignment in runway.ShouldAssignments:
                if node.Inbound.Report.plannedGate in runway.ShouldAssignments[RunwayAssignmentType.GateAssignment]:
                    shouldRunways.append(runway)

            if True == useETA:
                reference = node.ArrivalCandidates[runway.Runway.Name].EarliestArrivalTime
            else:
                reference = node.ArrivalCandidates[runway.Runway.Name].InitialArrivalTime

            # test the may assignments
            if RunwayAssignmentType.AircraftType in runway.MayAssignments:
                if node.Inbound.Report.aircraft.type in runway.MayAssignments[RunwayAssignmentType.AircraftType]:
                    eta, _ = self.calculateEarliestArrivalTime(runway.Runway.Name, node, useETA, earliestArrivalTime)
                    if (eta - reference) <= self.Configuration.AirportConfiguration.MaxDelayMay:
                        mayRunways.append(runway)
            if RunwayAssignmentType.GateAssignment in runway.MayAssignments:
                if node.Inbound.Report.plannedGate in runway.MayAssignments[RunwayAssignmentType.GateAssignment]:
                    eta, _ = self.calculateEarliestArrivalTime(runway.Runway.Name, node, useETA, earliestArrivalTime)
                    if (eta - reference) <= self.Configuration.AirportConfiguration.MaxDelayMay:
                        mayRunways.append(runway)

        runway = self.selectShallShouldMayArrivalRunway(node, shallRunways, useETA, earliestArrivalTime)
        if None != runway:
            return [ runway ]
        runway = self.selectShallShouldMayArrivalRunway(node, shouldRunways, useETA, earliestArrivalTime)
        if None != runway:
            return [ runway ]
        runway = self.selectShallShouldMayArrivalRunway(node, mayRunways, useETA, earliestArrivalTime)
        if None != runway:
            return [ runway ]

        return self.Configuration.RunwayConstraints.ActiveArrivalRunways

    def selectArrivalRunway(self, node : Node, useETA : bool, earliestArrivalTime : datetime):
        availableRunways = self.Configuration.RunwayConstraints.ActiveArrivalRunways

        if True == self.Configuration.RunwayConstraints.UseShallShouldMay:
            availableRunways = self.executeShallShouldMayAssignment(node, useETA, earliestArrivalTime)
        else:
            availableRunways = self.Configuration.RunwayConstraints.ActiveArrivalRunways

        if 0 == len(availableRunways):
            runway = self.Configuration.RunwayConstraints.ActiveArrivalRunways[0]
            return runway, self.calculateEarliestArrivalTime(runway.Runway.Name, node, useETA, earliestArrivalTime)

        # start with the beginning
        selectedRunway = None
        lostTime = None
        eta = None

        # get the runway with the earliest ETA
        for runway in availableRunways:
            candidate, delta = self.calculateEarliestArrivalTime(runway.Runway.Name, node, useETA, earliestArrivalTime)
            if None == eta or eta > candidate:
                selectedRunway = runway.Runway
                lostTime = delta
                eta = candidate

        return selectedRunway, eta, lostTime
