﻿using System;
using System.IO;

namespace Drecogrizer.Controls.Media
{
    public static class MediaExtensions
    {
        private static string _jpgExtension = ".jpg";

        public static void VerifyOptions(this CameraMediaOptions self)
        {
            if (self == null)
            {
                throw new ArgumentNullException(nameof(self));
            }
            if (Path.IsPathRooted(self.Directory))
            {
                throw new ArgumentException("options.Directory must be a relative path", nameof(self));
            }
        }

        public static string GetFilePath(this CameraMediaOptions self, string rootPath)
        {
            string name = self?.Name;
            
            if (String.IsNullOrWhiteSpace(name))
            {
                string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
                name = "IMG_" + timestamp + _jpgExtension;
            }

            string ext = Path.GetExtension(name);
            if (ext == String.Empty)
                ext = _jpgExtension;

            name = Path.GetFileNameWithoutExtension(name);

            string folder = Path.Combine(rootPath ?? String.Empty, self?.Directory ?? String.Empty);

            return Path.Combine(folder, name + ext);
        }

        public static string GetUniqueFilepath(this CameraMediaOptions self, string rootPath,
            Func<string, bool> checkExists)
        {
            string path = self.GetFilePath(rootPath);
            string folder = Path.GetDirectoryName(path);
            string ext = Path.GetExtension(path);
            string name = Path.GetFileNameWithoutExtension(path);

            string fullName = name + ext;
            int i = 1;
            while (checkExists(Path.Combine(folder, fullName)))
            {
                fullName = $"{name}_{(i++)}{ext}";
            }

            return Path.Combine(folder, fullName);
        }
    }
}