package com.torn.player;

import java.awt.Color;
import java.awt.Point;
import java.util.LinkedList;
import java.util.Queue;

import com.torn.enemy.AtomMoveManager;
import com.torn.tools.MyGraphics2D;

public class PlayerManager {
	private static PlayerManager playerManager = new PlayerManager();
	private Queue<Atom> atoms = new LinkedList<>();
	private static final int LIMIT_SIZE = 10;

	private PlayerManager() {

	}
	public static PlayerManager getInstance() {
		return playerManager;
	}

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

	/********/
	/* 描画 */
	/********/
	public void paint() {
		if (null == atoms) {
			return;
		}
		MyGraphics2D g2 = MyGraphics2D.getInstance();
		
		/* 描画 */
		for (int i = 0; i < atoms.size(); i++) {
			Atom[] array = atoms.toArray(new Atom[0]);
			Point p = new Point((int)(array[i].x + 0.5), (int)(array[i].y + 0.5));
			g2.setColor(Color.GREEN);
			g2.fillOval(p.x, p.y, 6, 6);
		}
	}
	
	/******************/
	/* 玉の移動・更新 */
	/******************/
	public void update() {
		if (atoms.isEmpty()) {
			return;
		}

		/* 移動 */
		move();
		
		/* 当たり判定 */
		hitCheck();
		
		/* ゴミ回収 */
		Atom atom = atoms.peek();
		if (atom.y <  -250) { // 仮
			atoms.poll();
		}
	}

	private static final int VEROCITY_Y = -2;
	public  void move() {
		if (atoms.isEmpty()) {
			return;
		}
		
		/* 上移動 */
		Atom[] array = atoms.toArray(new Atom[0]);
		for (int i = 0; i < atoms.size(); 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;
		}
		
		// 玉は一点判定
		for (int i = 0; i < array.length; i++) {
			Atom playerPt = array[i];
			int enemySize = 12;
			
			if (enemyPt.x <= playerPt.x  && playerPt.x <= enemyPt.x + enemySize &&
				enemyPt.y <= playerPt.y  && playerPt.y <= enemyPt.y + enemySize) {
				AtomMoveManager.getInstance().removeAtom(0);
				hitFlg = true;
			}
		}
		
		return hitFlg;
	}
}
