package com.engine;

import java.util.Random;

import javax.microedition.khronos.opengles.GL10;

import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.entity.Entity;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.opengl.texture.region.TextureRegion;

public class SpriteChain extends Entity {
	//private TextureRegion mTextureRegion;
	private Sprite[] mChainElementArray;
	private int mChainLength = 0;
	private float DELTA = 66f;
	public float speedX;
	public float speedY;

	private Random rand = new Random();
	
	public SpriteChain(TextureRegion[] tanimals,int pChainLength,float pX, float pY,float tSpeedX,float tSpeedY ) {
		//this.mTextureRegion = pTextureRegion;
		this.mChainLength = pChainLength;
		this.speedX=tSpeedX;
		this.speedY=tSpeedY;
				
		mChainElementArray = new Sprite[pChainLength];
		mChainElementArray[0] = spawnLink( tanimals,pX, pY);

		for (int i = 1; i < mChainLength; i++) {
			mChainElementArray[i] = spawnLink( tanimals,mChainElementArray[i - 1].getX(),
					mChainElementArray[i - 1].getY() + DELTA);
		}
	}

	@Override
	public void setPosition(float pX, float pY) {
		super.setPosition(pX, pY);

		mChainElementArray[0].setPosition(pX, pY);
		for (int i = 1; i < mChainLength; i++) {
			float dX = mChainElementArray[i - 1].getX()
					- mChainElementArray[i].getX();
			float dY = mChainElementArray[i - 1].getY()
					- mChainElementArray[i].getY();
			final float distance = (float) Math.sqrt(dX * dX + dY * dY);
			dX /= distance;
			dY /= distance;

			mChainElementArray[i].setPosition(mChainElementArray[i - 1].getX()
					- dX * DELTA, mChainElementArray[i - 1].getY()
					- dY * DELTA);
		}
	}

	private Sprite spawnLink(TextureRegion[] tanimals,float pX, float pY) {
		return this.spawnLink(tanimals,pX, pY, 1.0f);
	}

	private Sprite spawnLink(TextureRegion[] tanimals,float pX, float pY, float scale) {
		final Sprite chainLink = new Sprite(pX, pY, tanimals[rand.nextInt(8)]);
		chainLink.setWidth(64);
		chainLink.setHeight(64);
		chainLink.setScale(scale);
		return chainLink;
	}

        public void setDelta(float pDelta) {
                this.DELTA = pDelta;
        }

	@Override
	public float getX() {
		return mChainElementArray[0].getX();
	}

	@Override
	public float getY() {
		return mChainElementArray[0].getY();
	}

	@Override
	protected void onManagedDraw(final GL10 pGL, final Camera pCamera) {
		for (int i = 0; i < mChainElementArray.length; i++) {
			mChainElementArray[i].onDraw(pGL, pCamera);
		}
	}
}
