﻿using System.Windows.Threading;
using BranchSwitcher.Utilities;
using Microsoft.WindowsAPICodePack.Dialogs;
using SynNet.Services;

namespace BranchSwitcherUI.Services
{
	internal class OpenFileDialogService : IFolderPathDialogService
	{
		private readonly Dispatcher m_Dispatcher;

		public OpenFileDialogService(IDispatchLog dispatchHelper)
		{
			Guard.NotNull(dispatchHelper, nameof(dispatchHelper));
			m_Dispatcher = dispatchHelper.Dispatcher;
		}

		public string Query(string input)
		{
			if (!m_Dispatcher.CheckAccess())
			{
				return m_Dispatcher.Invoke(() => DoQuery(input));
			}
			else
			{
				return DoQuery(input);
			}
		}

		private string DoQuery(string input)
		{
			string folderPath = null;

			using (var dlg = new CommonOpenFileDialog())
			{
				dlg.Title = input ?? "";
				dlg.IsFolderPicker = true;
				dlg.InitialDirectory = "C:\\";
				dlg.AddToMostRecentlyUsedList = false;
				dlg.AllowNonFileSystemItems = false;
				dlg.DefaultDirectory = "C:\\";
				dlg.EnsureFileExists = true;
				dlg.EnsurePathExists = true;
				dlg.EnsureReadOnly = false;
				dlg.EnsureValidNames = true;
				dlg.Multiselect = false;
				dlg.ShowPlacesList = true;

				if (dlg.ShowDialog() == CommonFileDialogResult.Ok)
					folderPath = dlg.FileName;

				return folderPath;
			}
		}
	}
}

