/*
 *  Copyright (C) 2006-2021  Ronald Blankendaal
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
package org.dbgl.util;

import java.io.File;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.dbgl.model.ShortFile;


public class ShortFilenameUtils {

	public static List<File> convertToShortFileSet(List<File> fileList) {
		Set<ShortFile> result = new TreeSet<>();
		for (File file: fileList)
			result.add(createShortFile(file, result));
		return result.stream().map(x -> new File(x.getFile().getParentFile(), x.getName())).collect(Collectors.toList());
	}

	private static ShortFile createShortFile(File file, Set<ShortFile> curDir) {
		String filename = file.getName().toUpperCase();
		boolean createShort = false;
		if (StringUtils.contains(filename, ' ')) {
			filename = StringUtils.remove(filename, ' ');
			createShort = true;
		}
		int len = 0;
		int idx = filename.indexOf('.');
		if (idx != -1) {
			if (filename.length() - idx - 1 > 3) {
				filename = StringUtils.stripStart(filename, ".");
				createShort = true;
			}
			idx = filename.indexOf('.');
			len = (idx != -1) ? idx: filename.length();
		} else {
			len = filename.length();
		}
		createShort |= len > 8;

		ShortFile shortFile = null;
		if (!createShort) {
			shortFile = new ShortFile(file, StringUtils.removeEnd(filename, "."));
		} else {
			int i = 1;
			do {
				String nr = String.valueOf(i++);
				StringBuffer sb = new StringBuffer(StringUtils.left(filename, Math.min(8 - nr.length() - 1, len)));
				sb.append('~').append(nr);
				idx = filename.lastIndexOf('.');
				if (idx != -1)
					sb.append(StringUtils.left(filename.substring(idx), 4));
				shortFile = new ShortFile(file, StringUtils.removeEnd(sb.toString(), "."));
			} while (shortFile.isContainedIn(curDir));
		}
		return shortFile;
	}
}
