/*
 *  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.causeway.tooling.projectmodel.test;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;

import org.apache.causeway.commons.io.TextUtils;
import org.apache.causeway.tooling.projectmodel.gradle.GradleSettings;
import org.apache.causeway.tooling.projectmodel.gradle.GradleSettingsFactory;
import org.apache.causeway.tooling.projectmodel.gradle.GradleSettingsWriter;

import lombok.SneakyThrows;
import lombok.val;

class GradleSettingsTest extends ProjectModelTestAbstract {

    boolean hasUnresolvableGradleBuildArtifacts;

    @Override
    @BeforeEach
    void setUp() throws Exception {
        super.setUp();
        hasUnresolvableGradleBuildArtifacts = false;
    }

    @Test @Disabled("activate only if you want to see the settings.gradle written to stdout")
    void writeGradleSettingsToStdout() throws IOException {
        GradleSettings gradleSettings = GradleSettingsFactory.generateFromMaven(projRootFolder, "causeway");
        assertNotNull(gradleSettings);

        System.out.println();
        System.out.println();
        System.out.println(String.format("// generated by %s", this.getClass().getName()));
        System.out.println(String.format("// date %s", LocalDate.now().toString()));
        System.out.println();
        System.out.println(GradleSettingsWriter.toString(gradleSettings));
    }

    @Test
    void testGradleSettingGenerator() throws IOException {
        GradleSettings gradleSettings = GradleSettingsFactory.generateFromMaven(projRootFolder, "causeway");

        assertNotNull(gradleSettings);

        val knownBuildArtifactNames = new HashSet<String>();

        gradleSettings.getBuildArtifactsByArtifactKey().forEach((artifactKey, buildArtifact)->{
            knownBuildArtifactNames.add(buildArtifact.getName());
        });

        gradleSettings.getBuildArtifactsByArtifactKey().forEach((artifactKey, buildArtifact)->{

            if(buildArtifact.isRoot()) {
                return; // skip project's root
            }

            buildArtifact.getDefaultBuildFile()
            .ifPresent(buildFile->{
                checkBuildFile(buildFile, knownBuildArtifactNames);
            });

        });

        assertFalse(hasUnresolvableGradleBuildArtifacts);
    }

    // -- HELPER

    @SneakyThrows
    private void checkBuildFile(final File buildFile, final Set<String> knownBuildArtifactNames) {
        //System.out.println(String.format("checking %s", buildFile.getAbsolutePath()));

        val lines = TextUtils.readLinesFromFile(buildFile, StandardCharsets.UTF_8);
        for(val line : lines) {
            checkBuildFileLine(buildFile, line, knownBuildArtifactNames);
        }

    }

    private void checkBuildFileLine(final File buildFile, final String line, final Set<String> knownBuildArtifactNames) {
        val buildArtifactName = parseBuildArtifactName(line);
        if(buildArtifactName==null) {
            return;
        }
        if(!knownBuildArtifactNames.contains(buildArtifactName)) {
            hasUnresolvableGradleBuildArtifacts = true;
            System.err.println(String.format("not found '%s' in file '%s'", buildArtifactName, buildFile));
        }
    }

    //    compile project(':causeway-bom:causeway-schema')
    private String parseBuildArtifactName(final String line) {
        int p = line.indexOf("project('");
        if(p<0) {
            return null;
        }
        int start = p + 9;
        int end = line.indexOf("')", start);
        if(end<0) {
            return null;
        }
        val buildArtifactName = line.substring(start, end);
        return buildArtifactName;
    }

}
