package modeler;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.Icon;
import javax.swing.ImageIcon;

import net.java.games.jogl.GL;

/**
 * @author ags
 */
public class Light implements Treeable {

  protected String name;

  Icon icon = new ImageIcon("../icons/light.gif");

  public Icon getIcon() {

    return icon;
  }

  public static synchronized Light makeNewLight(boolean enabled) {

    if (!enabled) {
      return new Light(-1);
    }

    for (int ctr = 0; ctr < taken.length; ctr++) {
      if (taken[ctr] == false) {
        taken[ctr] = true;
        return new Light(ctr);
      }
    }
    return null;
  }

  public static synchronized void swapLights(DefaultMutableTreeNode root) {

    int count = 0;
    boolean[] newTaken = new boolean[8];
    for (int ctr = 0; ctr < root.getChildCount(); ctr++) {
      DefaultMutableTreeNode child = (DefaultMutableTreeNode) root.getChildAt(ctr);
      if (!(child.getUserObject() instanceof Light))
        continue;

      if (count >= 8) {
        throw new RuntimeException("Too many lights in new scene!");
      }
      newTaken[count] = true;
      ((Light) child.getUserObject()).id = ids[count];
      ((Light) child.getUserObject()).index = count;
      count++;
    }
    for (; count < 8; count++) {
      newTaken[count] = false;
    }

    for (int ctr = 0; ctr < 8; ctr++) {
      taken[ctr] = newTaken[ctr];
    }
  }

  public static synchronized void turnOnLights(GL gl) {

    for (int ctr = 0; ctr < taken.length; ctr++) {
      if (taken[ctr]) {
        gl.glEnable(ids[ctr]);
      }
      else {
        gl.glDisable(ids[ctr]);
      }
    }
  }

  public static synchronized void returnLight(Light l) {

    taken[l.index] = false;
  }

  protected final static boolean[] taken = { false, false, false, false, false, false, false, false };

  protected final static int[] ids = { GL.GL_LIGHT0, GL.GL_LIGHT1, GL.GL_LIGHT2, GL.GL_LIGHT3, GL.GL_LIGHT4, GL.GL_LIGHT5, GL.GL_LIGHT6, GL.GL_LIGHT7 };

  public int id;

  protected int index;

  public final float[] diffuse = new float[] { 1, 1, 1, 1 };

  public final float[] specular = new float[] { 0.4f, 0.4f, 0.4f, 1 };

  public final float[] position = new float[] { 1, 1, 1, 1 };

  private Light(int newIndex) {

    index = newIndex;
    if (index != -1) {
      id = ids[index];
    }
    setName("Light " + index);
  }

  public String toString() {

    return getName();
  }

  public void setName(String name) {

    this.name = name;

  }

  public String getName() {

    return name;
  }

}
