package com.conveyal.r5.transit.fare;

import com.conveyal.r5.api.util.Fare;
import com.conveyal.r5.api.util.Stop;
import com.conveyal.r5.util.P2;
import com.csvreader.CsvReader;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * Stop names are just strings. Only works on fares from a single feed.
 */
public class FareTable {

    private static final Logger LOG = LoggerFactory.getLogger(FareTable.class);

    private Map<P2<String>, Fare> fares = Maps.newHashMap();

    private boolean ignoreAgencyId;

    public FareTable (String name) {
        this(name, false);
    }

    public FareTable (String name, boolean ignoreAgencyId) {
        this.ignoreAgencyId = ignoreAgencyId;
        InputStream is = FareTable.class.getClassLoader().getResourceAsStream(name);
        CsvReader reader = new CsvReader(is, ',', Charset.forName("UTF-8"));
        try {
            reader.readHeaders();
            while (reader.readRecord()) {
                String from = reader.get("from_stop_id");
                String to = reader.get("to_stop_id");
                double low = Double.parseDouble(reader.get("low_fare"));
                double peak = Double.parseDouble(reader.get("peak_fare"));
                double senior = Double.parseDouble(reader.get("senior_fare"));
                Fare fare = new Fare(low, peak, senior);
                fares.put(new P2<String>(from, to), fare);
            }
        } catch (IOException ex) {
            LOG.error("Exception while loading fare table CSV.");
        }
    }

    public Fare lookup (String from, String to) {
        return new Fare(fares.get(new P2<String>(from, to))); // defensive copy, in case the caller discounts
    }

    public Fare lookup (Stop from, Stop to) {
        //TODO: how does this works WRT different GTFS feeds having Stops with same Ids?
        return this.ignoreAgencyId
                ? lookup(from.stopId.split(":")[1], to.stopId.split(":")[1])
                : lookup(from.stopId, to.stopId);
    }

}

@@ -1767,38 +1767,32 @@
 ares.get(new P2%3C
-String
 %3E(from, to))); /
@@ -1903,104 +1903,12 @@
     
-//TODO: how does this works WRT different GTFS feeds having Stops with same Ids?%0A        return 
+if (
 this
@@ -1922,19 +1922,20 @@
 AgencyId
-%0A  
+) %7B%0A
         
@@ -1942,19 +1942,35 @@
     
-  ? lookup(
+String fromWithoutFeedId = 
 from
@@ -1990,13 +1990,53 @@
 (%22:%22
+, 2
 )%5B1%5D
-,
+;%0A            String toWithoutFeedId =
  to.
@@ -2055,31 +2055,115 @@
 (%22:%22
+, 2
 )%5B1%5D
-)%0A                :
+;%0A            return lookup(fromWithoutFeedId, toWithoutFeedId);%0A        %7D else %7B%0A            return
  loo
@@ -2187,21 +2187,31 @@
 to.stopId);%0A
+        %7D%0A
     %7D%0A%0A%7D%0A

split only once to allow colons in the stop_id