//public PhotoInfo ReadExif2(string name)
		//{
		//	PhotoInfo info = new PhotoInfo() { FileName = name };

		//	using (MagickImage image = new MagickImage(name))
		//	{
		//		ExifProfile profile = image.GetExifProfile();

		//		ExifValue value = profile.GetValue(ExifTag.DateTimeDigitized);

		//		if (value.Value == null)
		//			throw new Exception("Неудалось считать дату и время файла");

		//		info.DateTimeDigitized = (DateTime)value.Value;

		//		value = profile.GetValue(ExifTag.Model);

		//		info.Model = (string)value.Value;

		//		if (info.Model == null)
		//			info.Model = "Неизвестная модель";

		//	}

		//	return info;
		//}

		public static void WriteExif(PhotoInfo info, int? quality)
        {
			// Для моего телефона не работает метод image.AddProfile. Т.к. для моего телефона дату менять ненадо, то пропускаем.
			if (info.Model.ToUpper().Contains("HUAWEI P7-L10"))
				return;

			using (MagickImage image = new MagickImage(info.FileName))
            {
				if (quality != null && quality < image.Quality)
					image.Quality = quality.Value;

                ExifProfile profile = image.GetExifProfile();

				if (profile == null)
					profile = new ExifProfile();

                profile.SetValue(ExifTag.DateTimeDigitized, info.DateTimeDigitized.ToString(DATE_TIME_FORMAT));
				profile.SetValue(ExifTag.DateTime, info.DateTimeDigitized.ToString(DATE_TIME_FORMAT));
				profile.SetValue(ExifTag.DateTimeOriginal, info.DateTimeDigitized.ToString(DATE_TIME_FORMAT));

				//try
				//{
					image.AddProfile(profile, true);

					image.Write(info.FileName);
				//}
				//catch (Exception exc)
				//{ 
				
				//}
            }
        }
        public PhotoInfo ReadExif(string name)
        {
            PhotoInfo info = new PhotoInfo() { FileName = name };

            using (ExifReader reader = new ExifReader(name))
            {
                reader.GetTagValue<DateTime>(ExifTags.DateTimeDigitized, out info.DateTimeDigitized);

                reader.GetTagValue<string>(ExifTags.Model, out info.Model);

                if (info.Model == null)
                    info.Model = "Неизвестная модель";
            }

            return info;
        }
		public static void Compress(PhotoInfo info, int quality)
		{
			using (MagickImage image = new MagickImage(info.FileName))
			{
				//ExifProfile profile = image.GetExifProfile();

				////try
				////{
				//image.AddProfile(profile);

				if (image.Quality <= quality)
					return;

					image.Quality = quality;

				image.Write(info.FileName);
				//}
				//catch { }


			}
		}
		private void UpdateAnalizedDate(PhotoInfo info)
		{
			if (dateFromExifRadioButton.Checked)
				info.DateTimeAnalized = info.DateTimeDigitized;
			else
			{
				string dateString = Path.GetFileName(info.FileName);
				
				foreach(string format in SUPPORTED_FILE_FORMATS)
					dateString = dateString.Replace($".{format}", "");

				info.DateTimeAnalized = DateTime.ParseExact(dateString, fromFileNameFormatTextBox.Text.Trim(), null);
			}
		}
        //Анализ папки
        private void AnalizeFolder()
        {
			try
			{
				List<string> files = new List<string>();
				
				foreach(string format in SUPPORTED_FILE_FORMATS)
					files.AddRange(Directory.GetFiles(directory, $"*.{format}"));

                sets = new Dictionary<string, List<PhotoInfo>>();

				//пробегаемся по файлам
				foreach (string name in files)
				{
					PhotoInfo info = null;

					try
					{
						info = exifFile.ReadExif(name);
					}
					catch (Exception exc)
					{
						this.BeginInvoke(new ShowMessageDelegate(ShowMessage), exc.Message);

						info = new PhotoInfo() { FileName = name, DateTimeAnalized = new DateTime(1900, 1, 1), DateTimeDigitized = new DateTime(1900,1,1), Model = "Не удалось считать Exif данные." };
					}

					UpdateAnalizedDate(info);

					DateTime date = info.DateTimeAnalized;

					// Если в наборе уже есть данная модель, добавляем информацию в список по этому набору
					if (sets.ContainsKey(info.Model))
					{
						List<PhotoInfo> list = sets[info.Model];

						while (list.Exists(x => x.DateTimeAnalized == date))
							date = date.AddSeconds(1);

						info.DateTimeAnalized = date;

						list.Add(info);
					}
					// Иначе создаем новый набор из одной информации
					else
						sets.Add(info.Model, new List<PhotoInfo>(new PhotoInfo[] { info }));


					ProgressScreen.PerformStep();
				}

                // Сортируем все списки
                foreach (List<PhotoInfo> list in sets.Values)
                    list.Sort((x1, x2) => { return x1.DateTimeAnalized.CompareTo(x2.DateTimeAnalized); });
            }
			catch (Exception exc)
			{
				this.BeginInvoke(new ShowMessageDelegate(ShowMessage), exc.Message);
			}
			finally
			{
				ProgressScreen.AbortProcessThread();
			}
        }