package com.torn.enemy;

import java.awt.Color;
import java.awt.Point;
import java.util.ArrayList;

import com.torn.tools.MyGraphics2D;

public class AtomMoveManager {
	private static AtomMoveManager atomManager = new AtomMoveManager();
	private ArrayList<MovableAtom> atoms = new ArrayList<>();

	private AtomMoveManager() {
		
	}

	public static AtomMoveManager getInstance() {
		return atomManager;
	}

	public void addAtom(int x, int y) {
		atoms.add(new MovableAtom(new Atom(x, y)));
	}
	public void addAllAtom(ArrayList<MovableAtom> array) {
		atoms.addAll(array);
	}

	public int getSize() {
		return atoms.size();
	}

	/* 描画クラスに必要な情報のみ渡す */
	public Point getAtomPoint(int index) {
		if (index >= atoms.size()) {
			return null;
		}
		Atom atom = atoms.get(index).getAtom();
		Point p = new Point((int)(atom.x + 0.5), (int)(atom.y + 0.5));
		return p;
	}

	public void removeAtom(int index) {
		atoms.remove(index);
	}

	/********/
	/* 定義 */
	/********/
	public void initAtom() {
		MyEnemy enemy = new MyEnemy();
		atoms.addAll(enemy.getAtoms());
	}

	/************/
	/* 移動制御 */
	/************/
	public void move() {
		for (int i = 0; i < getSize(); i++) {
			moveClockwise(i);				
		}
	}

	/**********************/
	/* 移動制御(動作定義) */
	/**********************/
	private static final double THETA = Math.PI / 12;

	public boolean moveClockwise(int index) {
		if (index >= atoms.size()) {
			return false;
		}

		double x, y;
		double r;
		double wt;
		double alpha;
		double dx, dy;

		/* 取得 */
		MovableAtom atom = atoms.get(index);
		x = atom.getX();
		y = atom.getY();
		r = atom.getR();
		wt = THETA * atom.t;
		alpha = atom.getAlpha();

		/* 座標計算 */
		dx = - r * THETA * Math.sin(wt + alpha);
		dy = r * THETA * Math.cos(wt + alpha);		
		atom.t++;

		/* 設定 */
		atom.setAtom(x + dx, y + dy, false);
		atoms.set(index, atom);
		
		return true;
	}
	public boolean moveAntiClockwise(int index) {
		if (index >= atoms.size()) {
			return false;
		}

		double x, y;
		double r;
		double wt;
		double alpha;
		double dx, dy;

		/* 取得 */
		MovableAtom atom = atoms.get(index);
		x = atom.getX();
		y = atom.getY();
		r = atom.getR();
		wt = THETA * atom.t;
		alpha = atom.getAlpha();
		
		/* 座標計算 */
		dx = - r * THETA * Math.sin(wt + alpha);
		dy = r * THETA * Math.cos(wt + alpha);		
		atom.t--;

		/* 設定 */
		atom.setAtom(x - dx, y - dy, false);
		atoms.set(index, atom);
		
		return true;
	}
	
	/********/
	/* 描画 */
	/********/
	private static final int ATOM_WIDTH = 12;
	private static final int ATOM_HEIGHT = 12;
	
	public void paint() {
		MyGraphics2D g2 = MyGraphics2D.getInstance();
		
		/* 描画 */
		for (int i = 0; i < getSize(); i++) {
			Point p = getAtomPoint(i);
			g2.setColor(Color.CYAN);
			g2.fillOval(p.x, p.y, ATOM_WIDTH, ATOM_HEIGHT);
		}
		
		if (!atoms.isEmpty()) {
			/* 描画(0番目を目立たせる) */
			Point p = getAtomPoint(0);
			g2.setColor(Color.RED);
			g2.drawOval(p.x, p.y, ATOM_WIDTH, ATOM_HEIGHT);
		}
	}

}