﻿/*****************************************************************************
*       Copyright 1985, 2020 Precisely.
*       All rights reserved.
*
*       This document contains unpublished, confidential, and proprietary
*       information of Precisely. No disclosure or use of any portion of
*       the contents of this document may be made without the express 
*       written consent of Precisely.
*****************************************************************************/

using System;
using System.AddIn.Pipeline;
using System.Collections.Generic;
using System.Windows;
using CustomFrameHelpers;
using MapInfo.Events;
using MapInfo.Types;
using SimpleInteractiveCustomFrameExample.Properties;

namespace MapInfo.MiPro.Samples.SimpleInteractiveCustomFrameExample
{
	public class SimpleInteractiveCustomFrameExample : ICustomFrameAddIn
	{
		// This internal collection is used to keep track of the Frames that this addin
		// has created.
		private IList<InteractiveCustomFrameControl> _addedFrames;
		protected IMapInfoPro MapInfoApplication;
		private IMapBasicApplication _currentInstance;
		private IMapInfoEvents _events;
		private IRibbonTab _interactiveCustomFrameTab;
		private EventHelper _eventHelper;

		public void SubscribeToEvents()
		{
			_events.LayoutFrameChanged += _eventHelper.EventsOnLayoutFrameChanged;
			_events.LayoutFrameResized += _eventHelper.EventsOnLayoutFrameResized;
			_events.LayoutFrameMoved += _eventHelper.EventsOnLayoutFrameMoved;
			_events.LayoutFrameMouseDown += _eventHelper.EventsOnLayoutFrameMouseDown;
			_events.LayoutFrameMouseUp += _eventHelper.EventsOnLayoutFrameMouseUp;
			_events.LayoutFrameMouseDoubleClicked += _eventHelper.EventsOnLayoutFrameMouseDoubleClicked;
			_events.LayoutFrameKeyDown += _eventHelper.EventsOnLayoutFrameKeyDown;
			_events.LayoutFrameKeyUp += _eventHelper.EventsOnLayoutFrameKeyUp;
			_events.LayoutSelectionChanged += _eventHelper.EventsOnLayoutSelectionChanged;
			_events.LayoutZoomChanged += _eventHelper.EventsOnLayoutZoomed;
		}

		public void UnSubscribeToEvents()
		{
			_events.LayoutFrameChanged -= _eventHelper.EventsOnLayoutFrameChanged;
			_events.LayoutFrameResized -= _eventHelper.EventsOnLayoutFrameResized;
			_events.LayoutFrameMoved -= _eventHelper.EventsOnLayoutFrameMoved;
			_events.LayoutFrameMouseDown -= _eventHelper.EventsOnLayoutFrameMouseDown;
			_events.LayoutFrameMouseUp -= _eventHelper.EventsOnLayoutFrameMouseUp;
			_events.LayoutFrameMouseDoubleClicked -= _eventHelper.EventsOnLayoutFrameMouseDoubleClicked;
			_events.LayoutFrameKeyDown -= _eventHelper.EventsOnLayoutFrameKeyDown;
			_events.LayoutFrameKeyUp -= _eventHelper.EventsOnLayoutFrameKeyUp;
			_events.LayoutSelectionChanged -= _eventHelper.EventsOnLayoutSelectionChanged;
			_events.LayoutZoomChanged -= _eventHelper.EventsOnLayoutZoomed;
		}

		public virtual void Initialize(IMapInfoPro mapInfoApplication, string mbxname)
		{
			//This helper method will make sure that Pack URIs will work.
			Helper.RegisterPackUri();

			// sets MapInfoApplication
			MapInfoApplication = mapInfoApplication;
			_eventHelper = new EventHelper(MapInfoApplication);
			_currentInstance = MapInfoApplication.GetMapBasicApplication(mbxname);
			_events = MapInfoEvents.InitializeEvents(mapInfoApplication, _currentInstance);
			_addedFrames = new List<InteractiveCustomFrameControl>();
			SubscribeToEvents();

			//Get Tabs count
			_interactiveCustomFrameTab = mapInfoApplication.Ribbon.Tabs.Add("InteractiveCustomFrames", Resources.Interactive_Tab_Caption);

			//add key tip to Ribbon
			_interactiveCustomFrameTab.KeyTip = Resources.Interactive_Tab_Keytip;

			//Adding group name Ribbon
			var bar = _interactiveCustomFrameTab.Groups.Add(Resources.Interactive_Tab_FrameGroup_Label);
			bar.IsLauncherVisible = true;

			//Delegating the method to show message box on launcher click
			bar.ToolTip = new MapInfoRibbonToolTip {ToolTipDescription = Resources.Interactive_Tab_ToolTip_Description, ToolTipText = Resources.Interactive_Tab_ToolTip_Text};

			var interactiveCustomFrameButton =
				bar.Controls.Add("InteractiveCustomFrameButton", Resources.InteractiveFrame_AddButton_Label) as IRibbonButtonControl;
			if (interactiveCustomFrameButton != null)
			{
				//Show button in large
				interactiveCustomFrameButton.IsLarge = true;

				//add key tip to button
				interactiveCustomFrameButton.KeyTip = "IF";

				//add the tooltip to HelloRibbon Button
				interactiveCustomFrameButton.ToolTip = new MapInfoRibbonToolTip
				{
					ToolTipDescription = Resources.InteractiveFrame_AddButton_ToolTip_Description,
					ToolTipText = Resources.InteractiveFrame_AddButton_ToolTip_DisabledText,
					ToolTipDisabledText = Resources.InteractiveFrame_AddButton_ToolTip_DisabledText
				};

				//Delegating the method to show message box on button click
				interactiveCustomFrameButton.Command =
					new DelegateCommand(AddInteractiveCustomFrame).ViewToContractAdapter();

				interactiveCustomFrameButton.CommandParameter = "Command Parameter";

				//add large Icon
				interactiveCustomFrameButton.LargeIcon =
					Helper.PathToUri("pack://application:,,,/MapInfo.StyleResources;component/Images/Application/about_64x64.png");

				//add small Icon
				interactiveCustomFrameButton.SmallIcon =
					Helper.PathToUri("pack://application:,,,/MapInfo.StyleResources;component/Images/Application/about_32x32.png");
			}

			//Take to focus selected to new Hello Ribbon Tab
			_interactiveCustomFrameTab.IsSelected = true;
		}

		public virtual void Reconstruct(string fileName, double xPosition, double yPosition, double width, double height,
			string penBorderClause, string borderBrushClause, int zIndex, string frameName)
		{
			if (string.IsNullOrEmpty(fileName))
			{
				throw new ArgumentNullException("fileName", Resources.FileLoading_Error_Message);
			}
			
			var customFrame = AddInCustomFrameSerializer.Deserialize(fileName) as InteractiveCustomFrameControl;

			if (customFrame != null)
			{
				customFrame.ControlContent = new InteractiveCustomFrameControlContent();

				customFrame.XCoord = new DimensionedValue(xPosition, PaperUnits.Inches);
				customFrame.YCoord = new DimensionedValue(yPosition, PaperUnits.Inches);
				customFrame.FrameWidth = new DimensionedValue(width, PaperUnits.Inches);
				customFrame.FrameHeight = new DimensionedValue(height, PaperUnits.Inches);
				customFrame.PenBorderClause = penBorderClause;
				customFrame.BrushClause = borderBrushClause;
				customFrame.ZIndex = zIndex;
				customFrame.FrameName = frameName;

				AddCustomFrameToLayout(customFrame);
			}
		}

		private void AddInteractiveCustomFrame(object sender)
		{
			var customFrameContent = new InteractiveCustomFrameControlContent();
			customFrameContent.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
			var controlSize = customFrameContent.DesiredSize;
			var customFrame = new InteractiveCustomFrameControl
			{
				FrameHeight = new DimensionedValue(controlSize.Height, PaperUnits.Pixels),
				FrameWidth = new DimensionedValue(controlSize.Width, PaperUnits.Pixels),
				ControlContent = customFrameContent
			};

			AddCustomFrameToLayout(customFrame);
		}

		private void AddCustomFrameToLayout(InteractiveCustomFrameControl customFrame)
		{
			var layoutWindow = Helper.FindFrontOrFirstLayoutDesigner(MapInfoApplication);
			if (layoutWindow != null)
			{
				var mapInfoCustomFrameWrapper =
					layoutWindow.AddActivatableFrameControl(customFrame, FrameType.CustomFrame) as ICustomFrameControl;
				if (mapInfoCustomFrameWrapper != null)
				{
					customFrame.WrapperControl = mapInfoCustomFrameWrapper;
					_addedFrames.Add(customFrame);

					mapInfoCustomFrameWrapper.SetContent(
						new NativeHandleContractInsulator(
							FrameworkElementAdapters.ViewToContractAdapter(customFrame.ControlContent)
							)
						);
					mapInfoCustomFrameWrapper.SetInactiveContent(new InactiveLayoutContent(customFrame.ControlContent));
				}
			}
		}

		public virtual void Unload()
		{
			UnSubscribeToEvents();

			_addedFrames.Clear();
			_addedFrames = null;
			if (_interactiveCustomFrameTab != null)
			{
				MapInfoApplication.Ribbon.Tabs.Remove(_interactiveCustomFrameTab);
			}
			_events = null;
			_currentInstance = null;
		}
	}
}