// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.restapi.zone.v2;

import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.config.provision.zone.ZoneList;
import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.container.jdisc.HttpResponse;
import com.yahoo.container.jdisc.LoggingRequestHandler;
import com.yahoo.restapi.ErrorResponse;
import com.yahoo.restapi.Path;
import com.yahoo.restapi.SlimeJsonResponse;
import com.yahoo.slime.Cursor;
import com.yahoo.slime.Slime;
import com.yahoo.vespa.flags.BooleanFlag;
import com.yahoo.vespa.flags.Flags;
import com.yahoo.vespa.hosted.controller.Controller;
import com.yahoo.vespa.hosted.controller.api.integration.ServiceRegistry;
import com.yahoo.vespa.hosted.controller.api.integration.zone.ZoneRegistry;
import com.yahoo.vespa.hosted.controller.auditlog.AuditLoggingRequestHandler;
import com.yahoo.vespa.hosted.controller.proxy.ConfigServerRestExecutor;
import com.yahoo.vespa.hosted.controller.proxy.ProxyRequest;
import com.yahoo.yolean.Exceptions;

import java.util.logging.Level;

/**
 * REST API for proxying requests to config servers in a given zone (version 2).
 *
 * This API does something completely different from /zone/v1, but such is the world.
 *
 * @author mpolden
 */
@SuppressWarnings("unused")
public class ZoneApiHandler extends AuditLoggingRequestHandler {

    private final ZoneRegistry zoneRegistry;
    private final ConfigServerRestExecutor proxy;
    private final BooleanFlag useConfigServerVip;

    public ZoneApiHandler(LoggingRequestHandler.Context parentCtx, ServiceRegistry serviceRegistry,
                          ConfigServerRestExecutor proxy, Controller controller) {
        super(parentCtx, controller.auditLogger());
        this.zoneRegistry = serviceRegistry.zoneRegistry();
        this.proxy = proxy;
        this.useConfigServerVip = Flags.USE_CONFIG_SERVER_VIP.bindTo(controller.flagSource());
    }

    @Override
    public HttpResponse auditAndHandle(HttpRequest request) {
        try {
            switch (request.getMethod()) {
                case GET:
                    return get(request);
                case POST:
                case PUT:
                case DELETE:
                case PATCH:
                    return proxy(request);
                default:
                    return ErrorResponse.methodNotAllowed("Method '" + request.getMethod() + "' is unsupported");
            }
        } catch (IllegalArgumentException e) {
            return ErrorResponse.badRequest(Exceptions.toMessageString(e));
        } catch (RuntimeException e) {
            log.log(Level.WARNING, "Unexpected error handling '" + request.getUri() + "', "
                                   + Exceptions.toMessageString(e));
            return ErrorResponse.internalServerError(Exceptions.toMessageString(e));
        }
    }

    private HttpResponse get(HttpRequest request) {
        Path path = new Path(request.getUri());
        if (path.matches("/zone/v2")) {
            return root(request);
        }
        return proxy(request);
    }

    private HttpResponse proxy(HttpRequest request) {
        Path path = new Path(request.getUri());
        if ( ! path.matches("/zone/v2/{environment}/{region}/{*}")) {
            return notFound(path);
        }
        ZoneId zoneId = ZoneId.from(path.get("environment"), path.get("region"));
        if ( ! zoneRegistry.hasZone(zoneId)) {
            throw new IllegalArgumentException("No such zone: " + zoneId.value());
        }
        return proxy.handle(proxyRequest(zoneId, path.getRest(), request));
    }

    private HttpResponse root(HttpRequest request) {
        Slime slime = new Slime();
        Cursor root = slime.setObject();
        Cursor uris = root.setArray("uris");
        ZoneList zoneList = zoneRegistry.zones().reachable();
        zoneList.zones().forEach(zone -> uris.addString(request.getUri()
                                                               .resolve("/zone/v2/")
                                                               .resolve(zone.getEnvironment().value() + "/")
                                                               .resolve(zone.getRegionName().value())
                                                               .toString()));
        Cursor zones = root.setArray("zones");
        zoneList.zones().forEach(zone -> {
            Cursor object = zones.addObject();
            object.setString("environment", zone.getEnvironment().value());
            object.setString("region", zone.getRegionName().value());
        });
        return new SlimeJsonResponse(slime);
    }

    private HttpResponse notFound(Path path) {
        return ErrorResponse.notFoundError("Nothing at " + path);
    }

    private ProxyRequest proxyRequest(ZoneId zoneId, String path, HttpRequest request) {
        // TODO: Still need to hardcode AWS since flag cannot be set until flag has been rolled out
        if (zoneId.region().value().startsWith("aws-") || useConfigServerVip.value()) {
            return ProxyRequest.tryOne(zoneRegistry.getConfigServerVipUri(zoneId), path, request);
        }
        return ProxyRequest.tryAll(zoneRegistry.getConfigServerUris(zoneId), path, request);
    }

}

@@ -622,27 +622,68 @@
 a.flags.
-BooleanFlag
+FetchVector;%0Aimport com.yahoo.vespa.flags.FlagSource
 ;%0Aimport
@@ -1608,38 +1608,29 @@
 nal 
-BooleanFlag useConfigServerVip
+FlagSource flagSource
 ;%0A%0A 
@@ -1968,64 +1968,21 @@
 his.
-useConfigServerVip = Flags.USE_CONFIG_SERVER_VIP.bindTo(
+flagSource = 
 cont
@@ -2000,17 +2000,16 @@
 Source()
-)
 ;%0A    %7D%0A
@@ -4915,32 +4915,195 @@
 uest request) %7B%0A
+        boolean useConfigServerVip = Flags.USE_CONFIG_SERVER_VIP.bindTo(flagSource)%0A                .with(FetchVector.Dimension.ZONE_ID, zoneId.value()).value();%0A%0A
         // TODO:
@@ -5262,24 +5262,16 @@
 erverVip
-.value()
 ) %7B%0A    

Use zone id as dimension when getting flag