﻿using System;
using System.Linq;
using System.Text;

namespace Hardcore.Web
{
    internal static class PathHider
    {
        public static bool Hide(string target, string pattern, out string hidden)
        {
            hidden = null;

            var nPattern = PathTools.NormPattern(pattern);
            var nTarget = PathTools.NormPath(target);
            
            var sPattern = nPattern.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            var sTarget = nTarget.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            var sOrigTarget = target.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

            var b = new StringBuilder();

            for (int i = 0; i < sTarget.Length; i++)
            {
                if (sPattern.Length == i)
                    return false;

                if (i != 0) b.Append("/");

                if (sPattern[i] == "..." &&
                    sPattern.Length - 1 == i)
                {
                    b.Append(string.Join("/", sOrigTarget, i, sTarget.Length - i));
                    hidden = b.ToString();
                    return true;
                }

                if (sPattern[i].Any(ch => ch != 'x'))
                {
                    if (sPattern[i].Any(ch => ch != '*') && sPattern[i] != sTarget[i])
                        return false;

                    b.Append(sOrigTarget[i]);
                }
                else
                {
                    b.Append("xxx");
                }
            }

            if (sPattern.Length == sTarget.Length)
            {
                hidden = b.ToString();
                return true;
            }

            hidden = null;
            return false;
        }
    }
}