/*
 * Copyright 2012 the original author or authors.
 *
 * 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.gradle.api.reporting.internal;

import com.googlecode.jatl.Html;
import org.gradle.api.UncheckedIOException;
import org.gradle.api.reporting.DirectoryReport;
import org.gradle.api.reporting.Report;
import org.gradle.util.GFileUtils;
import org.gradle.util.GradleVersion;

import java.io.*;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

public class BuildDashboardGenerator {
    private Set<Report> reports;
    private File outputFile;

    public BuildDashboardGenerator(Set<Report> reports, File outputFile) {
        this.reports = new TreeSet<Report>(new Comparator<Report>() {
            public int compare(Report o1, Report o2) {
                return o1.getDisplayName().compareTo(o2.getDisplayName());
            }
        });
        this.reports.addAll(reports);
        this.outputFile = outputFile;
    }

    public void generate() {
        try {
            GFileUtils.parentMkdirs(outputFile);
            Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8"));
            try {
                generate(writer);
            } finally {
                writer.close();
            }
            copyCss();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    private void copyCss() {
        GFileUtils.copyURLToFile(getClass().getResource("/org/gradle/reporting/base-style.css"), new File(outputFile.getParent(), "base-style.css"));
        GFileUtils.copyURLToFile(getClass().getResource("style.css"), new File(outputFile.getParent(), "style.css"));
    }

    private void generate(Writer writer) {
        new Html(writer) {{
            html();
                head();
                    meta().httpEquiv("Content-Type").content("text/html; charset=utf-8");
                    link().rel("stylesheet").type("text/css").href("base-style.css").end();
                    link().rel("stylesheet").type("text/css").href("style.css").end();
                    title().text("Build dashboard").end();
                end();
                body();
                div().id("content");
                    if (reports.size() > 0) {
                        h1().text("Build reports").end();
                        ul();
                        for (Report report : reports) {
                            li();
                            if (report.getDestination().exists()) {
                                a().href(GFileUtils.relativePath(outputFile.getParentFile(), getHtmlLinkedFileFromReport(report))).text(report.getDisplayName());
                            } else {
                                span().classAttr("unavailable").text(report.getDisplayName());
                            }
                            end(2);
                        }
                        end();
                    } else {
                        h1().text("There are no build reports available.").end();
                    }
                end();
                div().id("footer").text(String.format("Generated by %s", GradleVersion.current()));
            endAll();
        }};
    }

    private File getHtmlLinkedFileFromReport(Report report) {
        if(report instanceof DirectoryReport){
            return ((DirectoryReport) report).getEntryPoint();
        } else{
            return report.getDestination();
        }
    }
}
