module yamalib.draw.swallowdraw;

private import y4d_draw.screen;
private import y4d_draw.drawbase;
private import y4d_draw.texturebase;
private import y4d_draw.texturevector;
private import y4d_math.sintable;
private import y4d_math.rand;

private import yamalib.counterfsp;

class SwallowDraw {
	
	/// 表示するテクスチャの設定
	void setTexture(ITextureBase t_) {
		assert( !(t_ is null) );
		
		texture = t_;
	}
	
	/// 表示位置の設定
	void setXY(int x_, int y_) {
		x = x_;
		y = y_;
	}
	
	/// 終了までのステップ数の設定
	void setEndStep(int n) {
		endStep = n;
		rate.set(8*128, 64, n);
		length.set(length_val, 0, n);		
		alpha.set(0, 255, 10);
		angle.opAssign( rand.get(512) );
	}
	
	/// 中心点からの距離の設定
	void setLength(int n) {
		length_val = n;
	}
	
	/// 角速度の設定
	void setAngleSpeed(int n) {
		angle.setStep(n);
	}
	
	/// 描画が終了したか
	bool isEnd() {
		return cast(bool) (alpha.get()==0 && drawWait <= 0);
	}
	
	void setDrawWait(int n) {
		drawWait = n;
	}
	
	/// 状態のリセット
	void reset() {
		init = false;
		fadein = true;
		setEndStep( endStep );
	}

	/// 毎回呼び出すなり
	void onMove(Screen screen) {
		
		if (texture is null) return ;
		if (drawWait > 0) {
			drawWait--;
			return;
		}
		
		if (!init) {
			onInit();
			init = true;
		}
		
		int cx, cy, tx, ty;
	
		cx = cast(int) (screen.getWidth() / 2);
		cy = cast(int) (screen.getHeight() / 2);
		tx = cast(int) texture.getWidth();
		ty = cast(int) texture.getHeight();
				
		angle++;
		length++;
		rate++;
		alpha++;
		
		if (alpha.isEnd() && fadein) {
			fadein = false;
			alpha.set(255, 0, endStep);
		}
		
		x = cx + sin.sin(angle.get(), length.get());
		y = cy + sin.cos(angle.get(), length.get());
	}
	
	/// 毎回呼び出すなり
	void onDraw(Screen screen) {
		
		if (texture is null) return;
		if (drawWait > 0) {
			return;
		}
		
		Color4ub color = screen.getColor4ub();
		screen.setColor(255, 255, 255, alpha.get());

		
/+		TextureVector tv = cast(TextureVector) texture;
		TextureVector.TextureInfo[] tis = tv.getTextureInfo();
		
		float w=0, h=0;
		foreach(TextureVector.TextureInfo ti; tis) {
			w += ti.width;
			screen.bltRotate(ti.texture, 
				cast(int) (x+sin.sin(angle.get(),cast(int) w)),
				y + sin.cos(angle.get(),cast(int) w),
				angle.get(), rate.get()/128.0f, 4);
		}
+/
		screen.bltRotate(texture, x, y, angle.get(), rate.get()/128.0f, 4);
		
		screen.setColor( color );
	}
	
	
	/// コンストラクタ
	this() {
		sin = SinTable.get();
		rand = new Rand();
		rand.randomize();

		angle = new RootCounter();
		angle.set(0, 512, 1);
		
		length = new InteriorCounter();
		rate = new InteriorCounter();
		
		alpha = new InteriorCounter();
		
		length_val = 120;
	}
	
	~this() {
	}

private :

	static SinTable sin;
	static Rand rand;

	bool init;
	bool fadein;
	RootCounter angle;
	InteriorCounter length;
	InteriorCounter rate;
	InteriorCounter alpha;
	int x;
	int y;
	int endStep;
	int length_val;
	int drawWait;
	ITextureBase texture;
	
	
	
	/// 初期化処理
	void onInit() {
		
	}

}