/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2022 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed 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.jboss.installer.panels.frame;

import org.apache.commons.lang3.StringUtils;
import org.jboss.installer.core.Screen;

import java.util.ArrayList;
import java.util.List;

class IndexGenerator {
    private int counter = 1;
    private final List<Integer> index = new ArrayList<>();
    private Screen lastScreen = null;

    String nextScreen(Screen screen) {
        if (lastScreen != null && screen.getParent() != lastScreen.getParent()) {
            if (lastScreen == screen.getParent()) {
                index.add(counter - 1);
                counter = 1;
            } else {
                Screen tmp = lastScreen;
                while (screen.getParent() != tmp.getParent()) {
                    counter = index.get(index.size() - 1) + 1;
                    index.remove(index.size() - 1);
                    tmp = tmp.getParent();
                }
            }
        }
        lastScreen = screen;
        return joinIndex();
    }

    private String joinIndex() {
        final String existingIndex = StringUtils.join(index, ".");
        if(existingIndex.isEmpty()) {
            return "" + counter++;
        } else {
            return existingIndex + "." + counter++;
        }
    }
}
