/*
 * Copyright 2013 Yuichiro Moriguchi
 *
 * 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 net.morilib.sh.file;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

import net.morilib.sh.Sh;
import net.morilib.sh.ShFile;
import net.morilib.sh.ShFileSystem;
import net.morilib.sh.ShProcess;
import net.morilib.sh.misc.FileTypeUtils;

public class ShWindowsRealFile extends ShRealFile {

	public ShWindowsRealFile(ShFileSystem fs, String virtualpath,
			File file) {
		super(fs, virtualpath, file);
	}

	public Collection<ShFile> getFiles() {
		List<ShFile> l = new ArrayList<ShFile>();
		SortedSet<String> z;
		ShFile f;

		z = new TreeSet<String>(Arrays.asList(file.list()));
		for(String s : z) {
			f = new ShWindowsRealFile(filesystem,
					virtualpath + "/" + s, new File(file, s));
			l.add(f);
		}
		return l;
	}

	public ShProcess getProcess(String... args) {
		ProcessBuilder p;
		List<String> l;
		String[] a;

		if(file.getName().endsWith(".exe") &&
				FileTypeUtils.guessWindowsExecutable(file)) {
			if(filesystem.getSecurityPolicy().denyExecuteOSCommand()) {
				return null;
			}
			l = new ArrayList<String>(Arrays.asList(args));
			l.set(0, filesystem.getFile(l.get(0)).toString());
			p = new ProcessBuilder(l);
			return new ShOSProcess(p);
		} else if((a = FileTypeUtils.parseShebang(file)) != null &&
				a[1].equals(Sh.NAME)) {
			// TODO execute a script of this shell
			return null;
		} else if(a != null && a[0] != null && a[1] != null) {
			// TODO #! line
//			l = new ArrayList<String>();
//			s = a[0] + (a[0].equals("/") ? "" : "/") + a[1];
//			l.add(new File(s).toString());
//			if(a[2].length() > 0)  l.add(a[2]);
//			l.addAll(Arrays.asList(args));
//			p = new ProcessBuilder(l);
//			return new ShOSProcess(p);
			return null;
		} else {
			return null;
		}
	}

	public boolean isExecutable() {
		if(file.isDirectory()) {
			return true;
		} else if(file.isFile()) {
			return FileTypeUtils.parseShebang(file) != null;
		} else {
			return false;
		}
	}

}
