package net.liquidpineapple.pang.screens;

import net.liquidpineapple.pang.XmlHandler;
import net.liquidpineapple.pang.logger.Logger;

import org.xml.sax.SAXException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;

/**
 * Created by Tim on 10-10-2016.
 * Class that creates an iterator over the levels
 */
public abstract class LevelIterator {
  private ArrayList<Screen> levels = new ArrayList<>();

  public Iterator createIterator() {
    return levels.iterator();
  }

  /**
   * Method to fill the array with levels.
   *
   * @param path - path from where the levels should be loaded.
   */
  public void initArray(final String path) {
    List<String> filenames = new ArrayList<>();

    try(
        InputStream in = getResourceAsStream(path);
        BufferedReader br = new BufferedReader(new InputStreamReader(in))) {

      String resource;
      while((resource = br.readLine()) != null) {
        filenames.add(resource);
      }
    } catch (IOException e) {
      Logger.error(e.getMessage(), e);
    }

    for (String file : filenames) {
      Screen level;
      try {
        level = XmlHandler.createFromXml(path + file);
      } catch (IOException | ParserConfigurationException | SAXException e) {
        level = null;
        Logger.error(e.getMessage(), e);
      }
      if (level != null) {
        levels.add(level);
      } else {
        Logger.warning("Attempted to add null level");
      }
    }

    if (levels.size() == 0) {
      throw new ExceptionInInitializerError("Could not load levels, level array size was 0.");
    }
    Logger.info("Array initialized, " + levels.size() + " added to array");
  }

  private InputStream getResourceAsStream(String resource) {
    final InputStream in = getContextClassLoader().getResourceAsStream(resource);
    return in == null ? getClass().getResourceAsStream(resource) : in;
  }

  private ClassLoader getContextClassLoader() {
    return Thread.currentThread().getContextClassLoader();
  }
}

@@ -901,16 +901,17 @@
 %0A    try
+ 
 (%0A      
@@ -1068,16 +1068,17 @@
    while
+ 
 ((resour
@@ -1167,32 +1167,33 @@
 h (IOException e
+x
 ) %7B%0A      Logger
@@ -1192,32 +1192,33 @@
   Logger.error(e
+x
 .getMessage(), e
@@ -1213,24 +1213,25 @@
 Message(), e
+x
 );%0A    %7D%0A%0A  
@@ -1425,16 +1425,17 @@
 eption e
+x
 ) %7B%0A    
@@ -1474,16 +1474,17 @@
 .error(e
+x
 .getMess
@@ -1491,16 +1491,17 @@
 age(), e
+x
 );%0A     

Fix checkstyle in LevelIterator