package server;

import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

import server.match.levels.Level;
import server.match.objects.Ball;

public class LevelReader {
	/* LEVEL FILE READING, PARSING AND PLAYING */

	public static ArrayList<Level> readLevelsFromFiles() {
		ArrayList<Level> levels = new ArrayList<Level>();
		File root = new File(Main.class.getResource("/server/match/levels").getPath());
		File[] list = root.listFiles();
		for (File f : list) {
			if (f.isFile() && f.getName().endsWith(".bb")) {
				try {
					levels.add(readLevel(Files.readAllLines(f.toPath())));
				} catch (IOException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
					System.out.println("Level file corrputed");
					e.printStackTrace();
				}
			}
		}
		return levels;
	}

	private static Level readLevel(List<String> levelfile) throws NumberFormatException, IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
		Level level = new Level();
		if (levelfile.size() == 3) {
			int levelnum = Integer.parseInt(levelfile.get(0));
			level.setNum(levelnum);

			String[] ballsstrings = levelfile.get(1).split("\\|"); // split all
																	// the balls
			for (String ball : ballsstrings) {
				String[] ballstring = ball.split(",");
				if (ballstring.length == 7) {
					level.addBall(new Ball(Integer.parseInt(ballstring[0]), Integer.parseInt(ballstring[1]), (Color) Color.class.getField(ballstring[2]).get(null), Integer.parseInt(ballstring[3]), Integer.parseInt(ballstring[4]), Integer.parseInt(ballstring[5]), Double.parseDouble(ballstring[6])));
				}
			}

			level.setTime(Integer.parseInt(levelfile.get(2)));
		}
		return level;
	}
}
