﻿// <copyright file="StringExtensions.cs" company="TEAM Palow">
// Copyright (c) TEAM Palow. All rights reserved.
// </copyright>

using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

namespace Palow.Library.Extensions
{
    /// <summary>
    /// Extensions for strings.
    /// </summary>
    public static class StringExtensions
    {
        /// <summary>
        /// Return whether this is a directory.
        /// </summary>
        /// <param name="path">This path.</param>
        /// <returns>Whether the current path is a directory.</returns>
        public static bool IsDirectory(this string path)
        {
            return (File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory;
        }

        /// <summary>
        /// Cleans a file name from invalid chars.
        /// </summary>
        /// <param name="fileName">This file name.</param>
        /// <returns>A valid file name.</returns>
        public static string CleanFileName(this string fileName)
        {
            return Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(), string.Empty));
        }

        /// <summary>
        /// Converts a string to snake case.
        /// </summary>
        /// <param name="input">String to convert.</param>
        /// <returns>String as snake case.</returns>
        public static string ToSnakeCase(this string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return input;
            }

            var startUnderscores = Regex.Match(input, @"^_+");
            return startUnderscores + Regex.Replace(input, @"([a-z0-9])([A-Z])", "$1_$2").ToLower();
        }
    }
}