/*
 * Copyright 2009 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.integtests;

import org.apache.commons.io.FileUtils;
import org.gradle.api.UncheckedIOException;
import org.gradle.util.GFileUtils;
import org.gradle.util.CompressUtil;
import static org.junit.Assert.*;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.net.URI;
import java.net.URL;
import java.net.URISyntaxException;

public class TestFile extends File {
    public TestFile(File file, Object... path) {
        super(join(file, path).getAbsolutePath());
    }

    public TestFile(URI uri) {
        this(new File(uri));
    }

    public TestFile(URL url) {
        this(toUri(url));
    }

    private static URI toUri(URL url) {
        try {
            return url.toURI();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    private static File join(File file, Object[] path) {
        File current = GFileUtils.canonicalise(file);
        for (Object p : path) {
            current = GFileUtils.canonicalise(new File(current, p.toString()));
        }
        return current;
    }

    public TestFile file(Object... path) {
        return new TestFile(this, path);
    }

    public TestFile writelns(String... lines) {
        return writelns(Arrays.asList(lines));
    }

    public TestFile write(Object content) {
        try {
            FileUtils.writeStringToFile(this, content.toString());
        } catch (IOException e) {
            throw new UncheckedIOException(String.format("Could not write to test file '%s'", this), e);
        }
        return this;
    }

    public TestFile leftShift(Object content) {
        return write(content);
    }

    public String getText() {
        try {
            return FileUtils.readFileToString(this);
        } catch (IOException e) {
            throw new UncheckedIOException(String.format("Could not read from test file '%s'", this), e);
        }
    }

    public void unzipTo(File target) {
        CompressUtil.unzip(this, target);
    }

    public void copyTo(File target) {
        try {
            FileUtils.copyFile(this, target);
        } catch (IOException e) {
            throw new UncheckedIOException(String.format("Could not copy test file '%s' to '%s'", this, target), e);
        }
    }

    public void touch() {
        try {
            FileUtils.touch(this);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    @Override
    public String toString() {
        return getPath();
    }

    public TestFile writelns(Iterable<String> lines) {
        Formatter formatter = new Formatter();
        for (String line : lines) {
            formatter.format("%s%n", line);
        }
        return write(formatter);
    }

    public void assertExists() {
        assertTrue(String.format("%s does not exist", this), exists());
    }

    public void assertDoesNotExist() {
        assertFalse(String.format("%s should not exist", this), exists());
    }

    /**
     * Asserts that this file contains exactly the given set of descendants.
     */
    public void assertHasDescendants(String... descendants) {
        Set<String> actual = new TreeSet<String>();
        assertTrue(this.isDirectory());
        visit(actual, "", this);
        Set<String> expected = new TreeSet<String>(Arrays.asList(descendants));
        assertEquals(expected, actual);
    }

    private void visit(Set<String> names, String prefix, File file) {
        for (File child : file.listFiles()) {
            if (child.isFile()) {
                names.add(prefix + child.getName());
            } else if (child.isDirectory()) {
                visit(names, prefix + child.getName() + "/", child);
            }
        }
    }
}
