using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Vortex.Drawing;

namespace Vortex.Tutorials.MultiFormSupport {
	
	public partial class PopupForm : Form {		
		MultiContextDevice _drawingDevice;
		DrawingContext _targetContext;
		Texture _dropTexture;

		float _leadAngle;
		
		public PopupForm(MultiContextDevice drawingDevice) {
			InitializeComponent();

			_drawingDevice = drawingDevice;
			_targetContext = drawingDevice.CreateContext(Handle);
			_dropTexture = new Texture("data/graphics/drop.png");

			//it is important to setup next control styles to avoid flickering on resize
			SetStyle(ControlStyles.AllPaintingInWmPaint, true);
			SetStyle(ControlStyles.UserPaint, true);
			SetStyle(ControlStyles.Opaque, true);

			//update content on start
			UpdateContent();

			this.Disposed += new EventHandler(PopupForm_Disposed);
		}

		private void PopupForm_Disposed(object sender, EventArgs e) {
			//dispose all of unmanaged stuff
			_dropTexture.Dispose();
			_targetContext.Dispose();
		}

		private void PopupForm_Paint(object sender, PaintEventArgs e) {
			//just bring content from backbuffer
			_targetContext.Present();
		}

		private void UpdateContent() {
			//try to begin domain with current device
			if (_drawingDevice.BeginScene()) {
				Canvas2D canvas = _targetContext.Canvas;

				//clear target
				canvas.Clear((ColorU)SystemColors.Control);

				DrawContent(canvas);

				//end domain (finalizes some device stuff)
				_drawingDevice.EndScene();
				//present backbuffer content 
				_targetContext.Present();
			} else {
				//try reset drawing device
				_drawingDevice.TryReset();
			}
		}

		private void DrawContent(Canvas2D canvas) {
			Vector2 center = new Rect(ClientRectangle).Center;

			
			for (int n = 0; n < 10; ++n) {
				float angle = _leadAngle - n * 0.6f;

				//draw sprite 
				canvas.DrawSprite(
					new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle)) * 100 + center,
					_dropTexture.ToSprite().Resize(40, 40),
					ColorU.Aquamarine.MultiplyAlpha((10 - n) / 10f)
				);
			}
		}

		private void RateTimer_Tick(object sender, EventArgs e) {
			_leadAngle += 0.1f;
			UpdateContent();
		}
	}

}
