using System;
using System.Drawing;
public static class DisplayFusionFunction 
{
	public static void Run(IntPtr windowHandle) 
	{
        if (windowHandle == null) return;
        Rectangle windowBounds = BFS.Window.GetBounds(windowHandle);
        if (windowBounds == null) return;
        Rectangle screenBounds = BFS.Monitor.GetMonitorWorkAreaByWindow(windowHandle);
        if (screenBounds == null) return;
        var isRestored = BFS.Window.IsRestored(windowHandle);
        if (!isRestored) BFS.Window.Restore(windowHandle);
        var rightEdgeX =  screenBounds.X + screenBounds.Width -  windowBounds.Width;
        var bottomEdgeY = screenBounds.Y + screenBounds.Height - windowBounds.Height;
        Rectangle[] locations = new Rectangle[]
        {
            new Rectangle( screenBounds.X, screenBounds.Y, windowBounds.Width, windowBounds.Height), //   0,   0
            new Rectangle( rightEdgeX,     screenBounds.Y, windowBounds.Width, windowBounds.Height), // 100,   0
            new Rectangle( rightEdgeX,     bottomEdgeY,    windowBounds.Width, windowBounds.Height), // 100, 100
            new Rectangle( screenBounds.X, bottomEdgeY,    windowBounds.Width, windowBounds.Height), //   0, 100
        }; 
		// Start with the first location and look for the first matching X and Y
		Rectangle newLocation = locations[0];
		for(int i = 0; i < locations.Length; i++)
		{
			Rectangle location = locations[i];
			if (IsCloseEnough(windowBounds, location))
			{
				if (i < locations.Length - 1)
				{
					// Set the new location to the next location.
					// If it's the last location, use the already set first location.
					newLocation = locations[i+1];
				}				
				break;
			}
		}
		
		// Move the window to the new location
		BFS.Window.SetSizeAndLocation(windowHandle, newLocation.X, newLocation.Y, windowBounds.Width, windowBounds.Height);
	}
	// Checks to see if the upper left coordinates of each rectangle 
	// is within a tolerant number of pixels
	public static bool IsCloseEnough(Rectangle a, Rectangle b)
	{
		const int TOLERANCE = 50;
		int deltaX = a.X - b.X;
		if (deltaX < 0)
			deltaX = -deltaX;
		int deltaY = a.Y - b.Y;
		if (deltaY < 0)
			deltaY = -deltaY;
		return (deltaX <= TOLERANCE) && (deltaY <= TOLERANCE);
	}
}