﻿namespace RqTools.Models.Extensions
{
    using System;
    using System.Text;
    using System.Collections.Generic;

    /// <summary>
    /// Extensions for strings.
    /// </summary>
    public static class StringExtensions
    {
        public static string[] BlockString(this string value)
        {
            if (string.IsNullOrWhiteSpace(value))
                return new string[] { value };

            List<string> result = new List<string>(1024);

            string[] newLineParser;
            string[] wordParser;
            StringBuilder builder = new StringBuilder(512);

            newLineParser = value.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            for (int i = 0; i < newLineParser.Length; i++)
            {
                wordParser = newLineParser[i].Split(' ');
                foreach (var word in wordParser)
                {
                    if (builder.Length >= 50)
                    {
                        result.Add(builder.ToString());
                        builder.Clear();
                    }
                    builder.Append(word);
                    builder.Append(" ");
                }

                if (builder.Length > 0)
                {
                    result.Add(builder.ToString());
                }
                builder.Clear();

                result.Add(string.Empty); // NewLine!
            }
            return result.ToArray();
        }

        public static string CleanHtml(this string value)
        {
            if (string.IsNullOrWhiteSpace(value))
                return value;

            int p1;
            int p2;

            string tmp1;
            string tmp2;
            string work = string.Copy(value);

            work = work.Replace("<br />", Environment.NewLine);
            work = work.Replace("<br/>", Environment.NewLine);
            work = work.Replace("<br>", Environment.NewLine);

            work = work.Replace("&aacute;", "á");
            work = work.Replace("&eacute;", "é");
            work = work.Replace("&iacute;", "í");
            work = work.Replace("&oacute;", "ó");
            work = work.Replace("&uacute;", "ú");
            work = work.Replace("&nbsp;", " ");

            p1 = work.IndexOf('<');
            p2 = work.IndexOf('>', p1 + 1);

            while (p1 >= 0 && p2 > p1)
            {
                if (p1 == 0)
                {
                    tmp1 = "";
                }
                else
                {
                    tmp1 = work.Substring(0, p1);
                }
                tmp2 = work.Substring(p2 + 1);

                work = tmp1 + tmp2;

                p1 = work.IndexOf('<');
                p2 = work.IndexOf('>', p1 + 1);
            }
            return work;
        }
    }
}
