using System;
using FarseerGames.FarseerPhysics;
using FarseerGames.FarseerPhysics.Collisions;
using FarseerGames.FarseerPhysics.Dynamics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace FarseerPhysicsTutorial1 {

	public class Game1 : Microsoft.Xna.Framework.Game {
		GraphicsDeviceManager graphics;
		SpriteBatch spriteBatch;
		Drawer drawer;
		PhysicsSimulator world = new PhysicsSimulator();
		Body body = new Body();
		Geom geom;
		Body groundBody = new Body();
		Geom groundGeom;

		public Game1() {
			graphics = new GraphicsDeviceManager(this);
			graphics.PreferMultiSampling = true;
			TargetElapsedTime = TimeSpan.FromSeconds(1.0 / 240);
			Content.RootDirectory = "Content";

			world.Gravity = new Vector2(0, 9.8f);

			// 箱
			{
				world.Add(body);
				body.Rotation = 0.1f;
				var vertices = new Vertices(new Vector2[] {
					new Vector2(-1, -1),
					new Vector2(+1, -1),
					new Vector2(+1, +1),
					new Vector2(-1, +1),
				});
				vertices.SubDivideEdges(0.5f); // 辺を細分割する。
				geom = new Geom(body, vertices, 1);
				world.Add(geom);
			}

			// 地面
			{
				world.Add(groundBody);
				groundBody.IsStatic = true;
				var vertices = new Vertices(new Vector2[] {
					new Vector2(-10, +09),
					new Vector2(+10, +09),
					new Vector2(+10, +10),
					new Vector2(-10, +10),
				});
				vertices.SubDivideEdges(0.125f); // 辺を細分割する。
				groundGeom = new Geom(groundBody, vertices, 1);
				groundGeom.FrictionCoefficient = 0.05f;
				world.Add(groundGeom);
			}
		}

		protected override void LoadContent() {
			spriteBatch = new SpriteBatch(GraphicsDevice);
			drawer = new Drawer(GraphicsDevice);
		}

		protected override void Update(GameTime gameTime) {
			if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
				this.Exit();

			world.Update((float)gameTime.ElapsedGameTime.TotalSeconds);

			base.Update(gameTime);
		}

		void Draw(Geom geom) {
			drawer.DrawClosedPolyline(geom.WorldVertices.GetVerticesArray());
		}

		protected override void Draw(GameTime gameTime) {
			GraphicsDevice.Clear(Color.CornflowerBlue);

			var aspectRatio = GraphicsDevice.Viewport.AspectRatio;
			drawer.Begin(Matrix.CreateOrthographicOffCenter(-10 * aspectRatio, 10 * aspectRatio, 10, -10, -10, 10));
			Draw(geom);
			Draw(groundGeom);
			drawer.End();

			base.Draw(gameTime);
		}
	}
}
