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 {


	/// <summary>
	/// Demosntration of rendering in multiple windows simultaneously using Vortex2D.NET engine.
	/// </summary>
	public partial class MultiFormSupport : Form {
		private MultiContextDevice _drawingDevice;
		private DrawingContext _targetContext;
		private Texture _spaceshipTexture;

		public MultiFormSupport() {
			InitializeComponent();
			//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);			
		}

		private void MultiFormSupport_Load(object sender, EventArgs e) {
			_drawingDevice = new MultiContextDevice(this.Handle);
			_targetContext = _drawingDevice.CreateContext(this.Handle);
			_spaceshipTexture = new Texture("data/graphics/spacestation.png");

			this.Disposed += new EventHandler(PopupForm_Disposed);

			//draw content to make sure
			UpdateContent();
		}

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

		private void MultiFormSupport_Resize(object sender, EventArgs e) {
			//ask resize device when window size is changed
			_targetContext.Resize();
			//optionally you may call draw content
			UpdateContent();
		}

		private void MultiFormSupport_Paint(object sender, PaintEventArgs e) {
			//all we need is present content from back buffer
			_targetContext.Present();
		}

		private static readonly string TEXT_ON_WINDOW = "Primary window\n(double click to popup new window)";
		private void UpdateContent() {
			//try to begin domain with current device
			if (_drawingDevice.BeginScene()) {
				Canvas2D canvas = _targetContext.Canvas;

				//clear target
				canvas.Clear(ColorU.White);
				
				//draw sprite
				canvas.DrawSprite(new Rect(this.ClientRectangle).Deflate(20, 20), _spaceshipTexture.ToSprite(), ColorU.White);
				//draw text with shadow
				canvas.DrawText(SpriteFont.Default, new Vector2(5, 5), TEXT_ON_WINDOW, ColorU.Black.MultiplyAlpha(0.25f));
				canvas.DrawText(SpriteFont.Default, new Vector2(4, 4), TEXT_ON_WINDOW, ColorU.Navy);

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

		private void MultiFormSupport_DoubleClick(object sender, EventArgs e) {
			PopupForm popup = new PopupForm(_drawingDevice);
			popup.Show();
		}
	}
}
