/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.apache.tomcat.websocket.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import jakarta.websocket.DeploymentException;

import org.apache.tomcat.util.res.StringManager;

/**
 * Extracts path parameters from URIs used to create web socket connections using the URI template defined for the
 * associated Endpoint.
 */
public class UriTemplate {

    private static final StringManager sm = StringManager.getManager(UriTemplate.class);

    private final String normalized;
    private final List<Segment> segments = new ArrayList<>();
    private final boolean hasParameters;


    /**
     * Creates a new UriTemplate from the given path.
     *
     * @param path the URI template path
     * @throws DeploymentException if the path is invalid
     */
    public UriTemplate(String path) throws DeploymentException {

        if (path == null || !path.startsWith("/") || path.contains("/../") || path.contains("/./") ||
                path.contains("//")) {
            throw new DeploymentException(sm.getString("uriTemplate.invalidPath", path));
        }

        StringBuilder normalized = new StringBuilder(path.length());
        Set<String> paramNames = new HashSet<>();

        // Include empty segments.
        String[] segments = path.split("/", -1);
        int paramCount = 0;
        int segmentCount = 0;

        for (int i = 0; i < segments.length; i++) {
            String segment = segments[i];
            if (segment.isEmpty()) {
                if (i == 0) {
                    // Ignore the first empty segment as the path must always start with '/'.
                    continue;
                } else if (i == segments.length - 1) {
                    // Ending with a '/' is allowed.
                }
            }
            normalized.append('/');
            int index = -1;
            if (segment.startsWith("{") && segment.endsWith("}")) {
                index = segmentCount;
                segment = segment.substring(1, segment.length() - 1);
                normalized.append('{');
                normalized.append(paramCount++);
                normalized.append('}');
                if (!paramNames.add(segment)) {
                    throw new DeploymentException(sm.getString("uriTemplate.duplicateParameter", segment));
                }
            } else {
                if (segment.contains("{") || segment.contains("}")) {
                    throw new DeploymentException(sm.getString("uriTemplate.invalidSegment", segment, path));
                }
                normalized.append(segment);
            }
            this.segments.add(new Segment(index, segment));
            segmentCount++;
        }

        this.normalized = normalized.toString();
        this.hasParameters = paramCount > 0;
    }


    /**
     * Matches this template against a candidate URI path.
     *
     * @param candidate the candidate URI path
     * @return the path parameters if matched, or null
     */
    public Map<String,String> match(UriTemplate candidate) {

        Map<String,String> result = new HashMap<>();

        // Should not happen but for safety
        if (candidate.getSegmentCount() != getSegmentCount()) {
            return null;
        }

        Iterator<Segment> targetSegments = segments.iterator();

        for (Segment candidateSegment : candidate.getSegments()) {
            Segment targetSegment = targetSegments.next();

            if (targetSegment.parameterIndex() == -1) {
                // Not a parameter - values must match
                if (!targetSegment.value().equals(candidateSegment.value())) {
                    // Not a match. Stop here
                    return null;
                }
            } else {
                // Parameter
                result.put(targetSegment.value(), candidateSegment.value());
            }
        }

        return result;
    }


    /**
     * Returns whether this template contains path parameters.
     *
     * @return true if there are parameters
     */
    public boolean hasParameters() {
        return hasParameters;
    }


    /**
     * Returns the number of path segments.
     *
     * @return the segment count
     */
    public int getSegmentCount() {
        return segments.size();
    }


    /**
     * Returns the normalized path with numeric parameter indices.
     *
     * @return the normalized path
     */
    public String getNormalizedPath() {
        return normalized;
    }


    private List<Segment> getSegments() {
        return segments;
    }


    private record Segment(int parameterIndex, String value) {
    }
}
