package com.torn.player;

import java.util.ArrayList;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;

import com.torn.enemy.AtomMoveManager;

public class PlayerManager {
	private static PlayerManager playerManager = new PlayerManager();
	private static final int LIMIT_SIZE = 10;
	private ArrayList<Atom> atoms = new ArrayList<Atom>();
	
	private PlayerManager() {
	}
	public static PlayerManager getInstance() {
		return playerManager;
	}

	public synchronized boolean addAtom(float x, float y) {
		if (atoms.size() > LIMIT_SIZE) {
			/* 仮 */
			atoms.remove(0);
			if (atoms.size() > LIMIT_SIZE) {
				System.err.println("同期してない");
			}
		}
		atoms.add(new Atom(x, y));
		return true;
	}

	/******************/
	/* 玉の移動・更新 */
	/******************/
	public void update() {
		if (atoms.isEmpty()) {
			return;
		}

		/* 移動 */
		move();

		/* 当たり判定 */
		hitCheck();
		
		/* ゴミ回収 */
		Atom[] array = atoms.toArray(new Atom[0]);
		for (int i = 0; i < array.length; i++) {
			if (array[i].y <  25) { // 仮
				atoms.remove(i);
			}
		}
	}

	private static final int VEROCITY_Y = -4;
	public  void move() {
		if (atoms.isEmpty()) {
			return;
		}

		/* 上移動 */
		Atom[] array = atoms.toArray(new Atom[0]);
		for (int i = 0; i < array.length; i++) {
			array[i].y = array[i].y + VEROCITY_Y;
		}
	}

	private boolean hitCheck() {
		Atom[] array = atoms.toArray(new Atom[0]);		
		boolean hitFlg = false;

		// 敵は0番目しか見ていない(今の所)
		Point enemyPt = AtomMoveManager.getInstance().getAtomPoint(0);
		if (null == enemyPt) {
			return false;
		}

		int enemyR = AtomMoveManager.getInstance().getAtomRadius();

		// 玉は一点判定
		for (int i = 0; i < array.length; i++) {
			Atom playerPt = array[i];
	
			if (enemyPt.x - enemyR <= playerPt.x  && playerPt.x <= enemyPt.x + enemyR &&
				enemyPt.y - enemyR <= playerPt.y  && playerPt.y <= enemyPt.y + enemyR) {
				AtomMoveManager.getInstance().removeAtom(0);
				hitFlg = true;
			}
		}
	
	return hitFlg;
	}
	
	/********/
	/* 描画 */
	/********/
	private static final int ATOM_RADIUS = 6;
	public void paint(Canvas canvas) {
		if (atoms.isEmpty()) {
			return;
		}

		Paint paint = new Paint();
		paint.setColor(Color.GREEN);
		Atom[] array = atoms.toArray(new Atom[0]);
		for (int i = 0; i < array.length; i++) {
			canvas.drawCircle(array[i].x, array[i].y, ATOM_RADIUS, paint);
		}
	}
}
