/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.izpack;

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import com.izforge.izpack.api.data.InstallData;
import com.izforge.izpack.api.installer.DataValidator;

public class InstallPathValidator implements DataValidator  {

	@Override
	public boolean getDefaultAnswer() {
		return false;
	}

	@Override
	public String getErrorMessageId() {
		return "You cannot install Secure Data Manager in a folder that is not empty.";
		
		
	}

	@Override
	public String getWarningMessageId() {
		return null;
	}

	@Override
	public Status validateData(InstallData adata) {
		Path installPath = Paths.get(adata.getVariable("INSTALL_PATH"));
		try {
			if (Files.exists(installPath) && !isDirEmpty(installPath)){
				return Status.ERROR;
			} else {
				return Status.OK;
			}
		} catch (IOException e) {
			e.printStackTrace();
			return Status.ERROR;
		}
		
	}
	
	private boolean isDirEmpty(Path directory) throws IOException {
	    try(DirectoryStream<Path> dirStream = Files.newDirectoryStream(directory)) {
	        return !dirStream.iterator().hasNext();
	    }
	}

	
}
