using System.Text.RegularExpressions;

namespace ynhtm.Theme.Template
{
    public class ListProvider : IListProvider
    {
        public bool IsPageUrl(string url)
        {
            return Regex.IsMatch(url, @"/Page/\d+(/|\.\w+)?$", RegexOptions.Compiled | RegexOptions.RightToLeft | RegexOptions.IgnoreCase);
        }

        public string GetPageUrl(string url, int index)
        {
            return Regex.Replace(url, @"([^/]+)(/Page/\d+)?(/|\.\w+)?$", "$1/Page/" + index + "$3", RegexOptions.Compiled | RegexOptions.RightToLeft | RegexOptions.IgnoreCase);
        }

        public string GetFirstUrl(string url)
        {
            return Regex.Replace(url, @"([^/]+)(/Page/\d+)?(/|\.\w+)?$", "$1$3", RegexOptions.Compiled | RegexOptions.RightToLeft | RegexOptions.IgnoreCase);
        }

        public string GetLastUrl(string url, int pageCount)
        {
            if (pageCount <= 1) return this.GetFirstUrl(url);
            return this.GetPageUrl(url, pageCount);
        }

        public string GetPrevUrl(string url)
        {
            var index = this.GetPageIndex(url);
            if (index < 3) return this.GetFirstUrl(url);
            return this.GetPageUrl(url, index - 1);
        }

        public string GetNextUrl(string url, int pageCount)
        {
            var index = this.GetPageIndex(url);
            if (index >= pageCount) return this.GetLastUrl(url, pageCount);
            return this.GetPageUrl(url, index + 1);
        }

        public int GetPageIndex(string url)
        {
            var m = Regex.Match(url, @"[^/]+/Page/(\d+)(/|\.\w+)?$", RegexOptions.Compiled | RegexOptions.RightToLeft | RegexOptions.IgnoreCase);
            if (!m.Success) return 1;
            var index = int.Parse(m.Result("$1"));
            if (index < 1) return 1;
            return index;
        }

        public string GetSourceUrl(string url)
        {
            return this.GetFirstUrl(url);
        }
    }
}