using System.Windows.Forms;
using Microsoft.VisualBasic;
using System;
using MicroFour.StrataFrame.Business;
using StrataFlix.Business;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Drawing;


namespace StrataFlix
{
	public partial class MovieMaintenance
	{
		
		#region " Constructors "
		
		/// <summary>
		/// Default constructor
		/// </summary>
		/// <remarks></remarks>
		public MovieMaintenance()
		{
			
			// This call is required by the Windows Form Designer.
			InitializeComponent();
			
			//-- Load the images
			LoadImages();
			
			//-- Ensure that the home page is initially shown
			pmMain.SetActivePage(PageHome);
			
		}
		
		#endregion
		
		#region " Handled Events "
		
		private void action_PrintProfile_Click()
		{
			if (this.pmMain.CurrentPage.Equals(PageEditor))
			{
				//-- Create a reporting data source directly to prevent the browse from appearing for selection
				//   since we already have a record loaded and want to print the loaded record.
				Reporting.Reports.MovieProfile.MovieProfileDataSource rptSource = new Reporting.Reports.MovieProfile.MovieProfileDataSource();
				
				//-- Manually populate the report data source using the currently loaded movie record
				rptSource.PopulateDefinedDataSource(Movies.mv_pk, true);
				
				//-- Run the report using the specified data source
				Reporting.ReportEngine.RunReport(rptSource);
			}
			else
			{
				Reporting.ReportEngine.RunReport(Reporting.StrataFlixReports.MovieProfile);
			}
			
		}
		
		private void action_Print_Click()
		{
			Reporting.ReportEngine.RunReport(Reporting.StrataFlixReports.MovieListing);
		}
		
		private void cmdFormatAdd_Click(object sender, System.EventArgs e)
		{
			AddMediaFormat();
		}
		
		private void lstMediaFormats_RowPopulating(MicroFour.StrataFrame.UI.Windows.Forms.RowPopulatingEventArgs e)
		{
			//-- Establish Locals
			MovieItemsBO bo = (MovieItemsBO) e.BusinessObject;
			
			//-- Get the full genre type
			e.Values[0].DisplayValue = MicroFour.StrataFrame.Tools.Common.GetEnumDisplayValue(bo.mvi_Format);
		}
		
		private void lstMediaFormats_ListPopulating(MicroFour.StrataFrame.UI.ListPopulatingEventArgs e)
		{
			//-- Create a temporary object from which to fill the list.  This is done to prevent
			//   movement on the CurrentRowIndex and to keep the filter from being applied on the
			//   BO instance on the dialog.
			using (MovieItemsBO bo = new MovieItemsBO())
			{
				//-- Copy the data
				bo.CopyDataFrom(MovieItems, BusinessCloneDataType.ClearAndFillFromDefaultView);
				
				//-- Set a filter (only include media formats)
				bo.Filter = "mvi_Type = 1";
				
				//-- Now set the parms for the list
				e.Parameters[0].Value = bo;
				e.Parameters[1].Value = BusinessCloneDataType.ClearAndFillFromDefaultView;
			}
			
		}
		
		private void cmdGenreAdd_Click(object sender, System.EventArgs e)
		{
			AddGenre();
		}
		
		private void lstGenres_RowPopulating(MicroFour.StrataFrame.UI.Windows.Forms.RowPopulatingEventArgs e)
		{
			//-- Establish Locals
			MovieItemsBO bo = (MovieItemsBO) e.BusinessObject;
			
			//-- Get the full genre type
			e.Values[0].DisplayValue = MicroFour.StrataFrame.Tools.Common.GetEnumDisplayValue(bo.mvi_Genre);
		}
		
		private void lstGenres_ListPopulating(MicroFour.StrataFrame.UI.ListPopulatingEventArgs e)
		{
			//-- Create a temporary object from which to fill the list.  This is done to prevent
			//   movement on the CurrentRowIndex and to keep the filter from being applied on the
			//   BO instance on the dialog.
			using (MovieItemsBO bo = new MovieItemsBO())
			{
				//-- Copy the data
				bo.CopyDataFrom(MovieItems, BusinessCloneDataType.ClearAndFillFromDefaultView);
				
				//-- Set a filter
				bo.Filter = "mvi_Type = 0";
				
				//-- Now set the parms for the list
				e.Parameters[0].Value = bo;
				e.Parameters[1].Value = BusinessCloneDataType.ClearAndFillFromDefaultView;
			}
			
			
			
		}
		
		private void action_Delete_Click()
		{
			DeleteRecord();
		}
		
		private void action_Add_Click()
		{
			AddRecord();
		}
		
		private void lnkAddMovie_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
		{
			AddRecord();
		}
		
		private void action_ClearPosterImage_Click()
		{
			ClearMoviePoster();
		}
		
		private void action_AttachPosterImage_Click()
		{
			AttachMoviePoster();
		}
		
		private void MovieMaintenance_AfterUndo(MicroFour.StrataFrame.Data.AfterSaveUndoByFormEventArgs e)
		{
			//-- See if there are any records within the movies BO
			if (Movies.Count > 0)
			{
				//-- Reload the data from the server
				LoadAllDataForMovie(Movies.mv_pk, true);
				
				//-- Requery the lists
				lstCast.Requery();
				lstGenres.Requery();
				lstMediaFormats.Requery();
				
				//-- Set the object states
				SetObjectStates();
			}
			else
			{
				//-- Force the display back to the getting started page
				pmMain.SetActivePage(PageHome);
			}
		}
		
		private void lstCast_ChildFormResults(System.Object sender, MicroFour.StrataFrame.UI.Windows.Forms.ListViewChildFormResultsEventArgs e)
		{
			if (e.Results == System.Windows.Forms.DialogResult.Cancel)
			{
				MovieCast.RestoreCurrentDataTableSnapshot(false);
			}
			else
			{
				e.Requery = true;
			}
		}
		
		private void lstCast_ListPopulating(MicroFour.StrataFrame.UI.ListPopulatingEventArgs e)
		{
			e.Parameters[0].Value = MovieCast;
			e.Parameters[1].Value = MicroFour.StrataFrame.Business.BusinessCloneDataType.ClearAndFillFromDefaultView;
		}
		
		private void lstCast_RowPopulating(MicroFour.StrataFrame.UI.Windows.Forms.RowPopulatingEventArgs e)
		{
			//-- Establish Locals
			MovieCastBO bo = (MovieCastBO) e.BusinessObject;
			
			//-- Group by the cast types
			e.UseGroup = true;
			
			//-- Set the image and header text
			switch (bo.mc_CastType)
			{
				case MovieCastType.Actor:
					e.ImageKey = "Actor";
					e.GroupHeaderText = "Actors";
					break;
					
				case MovieCastType.Crew:
					e.ImageKey = "Crew";
					e.GroupHeaderText = "Crew";
					break;
					
				case MovieCastType.Director:
					e.ImageKey = "Director";
					e.GroupHeaderText = "Directors";
					break;
					
				case MovieCastType.Producer:
					e.ImageKey = "Producer";
					e.GroupHeaderText = "Producers";
					break;
					
				default:
					e.ImageKey = "Actor";
					e.GroupHeaderText = "Actors";
					break;
			}
		}
		
		private void PageHome_PageActivated(MicroFour.StrataFrame.UI.Windows.Forms.PanelPageEventArgs e)
		{
			SetObjectStates();
		}
		
		private void action_GettingStarted_Click()
		{
			pmMain.SetActivePage(PageHome);
		}
		
		private void PageEditor_PageActivated(MicroFour.StrataFrame.UI.Windows.Forms.PanelPageEventArgs e)
		{
			SetObjectStates();
		}
		
		private void action_Search_Click()
		{
			SearchForRecord();
		}
		
		private void lnkFindMovie_LinkClicked(System.Object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
		{
			SearchForRecord();
		}
		
		#endregion
		
		#region " Private Methods "
		
		/// <summary>
		/// Adds a new genre to the collection
		/// </summary>
		/// <remarks></remarks>
		private void AddGenre()
		{
			//-- Establish Locals
			List<string> omit = new List<string>();
			GenreSelection f;
			
			//-- Cycle through all of the genre records and build the omition collection
			foreach (MovieItemsBO bo in MovieItems.GetEnumerable())
			{
				//-- Skip any record not of a genre type
				if (bo.mvi_Type != MovieItemType.Genre)
				{
					continue;
				}
				
				//-- Add the item to the collection
				omit.Add(bo.mvi_Genre.ToString());
			}
			
			//-- Create and show the dialog
			f = new GenreSelection(omit.ToArray());
			
			//-- Show the dialog
			if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			{
				//-- A value was selected, so add a new record
				MovieItems.NewRow();
				MovieItems.mvi_Type = MovieItemType.Genre;
				MovieItems.mvi_Genre = f.SelectedGenre;
				
				//-- Requery the list
				lstGenres.Requery();
			}
			
			//-- Clean Up
			f.Close();
			f.Dispose();
		}
		
		/// <summary>
		/// Adds a new media format to the collection
		/// </summary>
		/// <remarks></remarks>
		private void AddMediaFormat()
		{
			//-- Establish Locals
			List<string> omit = new List<string>();
			MediaFormatSelection f;
			
			//-- Cycle through all of the genre records and build the omition collection
			foreach (MovieItemsBO bo in MovieItems.GetEnumerable())
			{
				//-- Skip any record not of a media format type
				if (bo.mvi_Type != MovieItemType.Format)
				{
					continue;
				}
				
				//-- Add the item to the collection
				omit.Add(bo.mvi_Format.ToString());
			}
			
			//-- Create and show the dialog
			f = new MediaFormatSelection(omit.ToArray());
			
			//-- Show the dialog
			if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			{
				//-- A value was selected, so add a new record
				MovieItems.NewRow();
				MovieItems.mvi_Type = MovieItemType.Format;
				MovieItems.mvi_Format = f.SelectedMediaFormat;
				
				//-- Requery the list
				lstMediaFormats.Requery();
			}
			
			//-- Clean Up
			f.Close();
			f.Dispose();
		}
		
		/// <summary>
		/// Adds a new record
		/// </summary>
		/// <remarks></remarks>
		private void AddRecord()
		{
			//-- Add the new movie record
			Movies.Add();
			
			//-- Clear any BOs that may have been filled from previous records
			MovieCast.Clear();
			MovieItems.Clear();
			MovieImages.Clear();
			
			//-- Ensure that the editor page is active
			if (!(pmMain.CurrentPage.Equals(PageEditor)))
			{
				pmMain.SetActivePage(PageEditor);
			}
			
			//-- Requery the lists
			lstCast.Requery();
			lstGenres.Requery();
			lstMediaFormats.Requery();
			
			//-- Set the object states
			SetObjectStates();
			
			//-- Refresh the image
			imgMoviePoster.Image = MovieImages.mi_PosterLarge;
			
			//-- Set the focus to the title field
			//txtTitle.Focus();
		}
		
		/// <summary>
		/// Attaches a movie poster image
		/// </summary>
		/// <remarks></remarks>
		private void AttachMoviePoster()
		{
			if (this.selectMoviePoster.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			{
				//-- Ensure that a movie image record exists
				if (MovieImages.Count == 0)
				{
					MovieImages.NewRow();
				}
				
				//-- Set the movie poster
				MovieImages.mi_PosterLarge = Basics.ReduceImageSize((Image) (new Bitmap(selectMoviePoster.FileName)),94,139);
				
				//-- Update the object states
				SetObjectStates();
				
				//-- Refresh the binding
				MovieImages.Refresh();
			}
		}
		
		/// <summary>
		/// Deletes the currently loaded record
		/// </summary>
		/// <remarks></remarks>
		private void DeleteRecord()
		{
			if (MicroFour.StrataFrame.Messaging.MessageForm.ShowMessageByKey("MovieMaintenance_Delete", Movies.mv_Title) == MicroFour.StrataFrame.Messaging.MessageFunctionType.Yes)
			{
				//-- Delete the record
				Movies.DeleteCurrentRow(false);
				
				//-- Return to the getting started page
				this.pmMain.SetActivePage(PageHome);
			}
		}
		
		/// <summary>
		/// Clears the attached movie poster
		/// </summary>
		/// <remarks></remarks>
		private void ClearMoviePoster()
		{
			//-- Clear out the image
			MovieImages.mi_ImageData = new byte[] {};
			
			//-- Reset the object states
			SetObjectStates();
			
			//-- Refresh the binding for the image
			MovieImages.Refresh();
		}
		
		/// <summary>
		/// Retrieves all of the data that will be used within this dialog
		/// </summary>
		/// <remarks></remarks>
		private void LoadAllDataForMovie(int moviePk, bool includeMovieRecord)
		{
			//-- Perform the query and retrieve the data
			if (includeMovieRecord)
			{
				BusinessLayer.FillMultipleDataTables(ApplicationQueries.MovieMaintenance_AllData(moviePk, includeMovieRecord), Movies, MovieCast, MovieItems, MovieImages);
			}
			else
			{
				BusinessLayer.FillMultipleDataTables(ApplicationQueries.MovieMaintenance_AllData(moviePk, includeMovieRecord), MovieCast, MovieItems, MovieImages);
			}
			
			//-- Reset the image poster to the default.  The reason this is being done in code instead of through binding
			//   is because when a BO doesn't have any rows, the bindings are removed. Yet we still want to show that there is no
			//   movie poster (or the default movie poster).
			if (MovieImages.Count == 0)
			{
				imgMoviePoster.Image = MovieImages.mi_PosterLarge;
			}
		}
		
		/// <summary>
		/// Loads the images from the resource files into the image list. The reason this is done
		/// in code is to improve the quality of the images over multiple compiles.  When added to the ImageList
		/// control through the designer the control will reduce the quality of the images after a number of compiles
		/// which will then begin to make the images look grainly and as though the edges bleed into the background instead
		/// of remaining crisp.  One way to prevent this from happening is to manually load the images into the image list
		/// at run-time which will prevent this from happening.
		/// </summary>
		/// <remarks></remarks>
		private void LoadImages()
		{
			imgImages.Images.Add("Actor", global::StrataFlix.Properties.MovieResources.Actor_16);
			imgImages.Images.Add("Director", global::StrataFlix.Properties.MovieResources.Director_16);
			imgImages.Images.Add("Crew", global::StrataFlix.Properties.MovieResources.crew_16);
			imgImages.Images.Add("Producer", global::StrataFlix.Properties.MovieResources.Producer_16);
		}
		
		/// <summary>
		/// Performs a search for a particular record
		/// </summary>
		/// <remarks></remarks>
		private void SearchForRecord()
		{
			//-- Show the browse dialog
			if (MoviesBrowseDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			{
				//-- Retrieve all of the movie data
				LoadAllDataForMovie(Movies.mv_pk, false);
				
				//-- Reload the cast list
				lstCast.Requery();
				lstGenres.Requery();
				lstMediaFormats.Requery();
				
				//-- Since a record was selected, show the editor page
				pmMain.SetActivePage(PageEditor);
			}
		}
		
		#endregion
		
		#region " Protected Methods "
		
		/// <summary>
		/// Sets the objects state of items within this dialog
		/// </summary>
		/// <remarks></remarks>
		protected override void SetObjectStates()
		{
			//-- Establish Locals
			bool isDirty = Movies.IsDirty || MovieCast.IsDirty || MovieImages.IsDirty || MovieItems.IsDirty;
			
			//-- Set the actions
			action_GettingStarted.Enabled = (! isDirty) && (!(pmMain.CurrentPage.Equals(PageHome)));
			action_Add.Enabled = ! isDirty;
			action_Search.Enabled = ! isDirty;
			action_Print.Enabled = ! isDirty;
			action_PrintProfile.Enabled = ! isDirty;
			action_Delete.Enabled = ! isDirty && (pmMain.CurrentPage.Equals(PageEditor));
			action_AttachPosterImage.Visible = Movies.Count > 0 && (pmMain.CurrentPage.Equals(PageEditor));
			action_ClearPosterImage.Visible = Movies.Count > 0 && (pmMain.CurrentPage.Equals(PageEditor)) && MovieImages.HasMoviePoster();
			
			
			//-- Determine if the additional separator should be displayed
			sep_Additional.Visible = action_AttachPosterImage.Visible || action_ClearPosterImage.Visible;
		}
		
		#endregion

        private void cmdAdd_Click(object sender, EventArgs e)
        {

        }

        private void MovieMaintenance_Load(object sender, EventArgs e)
        {

        }
		
	}
	
}
