using Concilium.Helpers;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Concilium.Bot.Features
{
    [BotFeature(".joke")]
    public class JokeFeature : BotFeatureBase
    {
        public override void Execute(string _sCommand, string _sSource, string _sTarget, string _sMessage, IList<string> _parameters, string _ip)
        {
            string target = "";
            if (_parameters.Count == 1)
                target = _parameters[0];
            else if (_parameters.Count > 1)
                throw new InvalidCommandParametersException(".joke", 1);
            else
            {
                var minDate = DateTime.Now;

                foreach (var entry in Concilium.Data.Info)
                {
                    if (entry.Value.LastWritten.HasValue && entry.Value.LastWritten.Value < minDate)
                    {
                        minDate = entry.Value.LastWritten.Value;
                        target = entry.Key;
                    }
                }

                if (target == "")
                    target = "Concilium";
            }

            var wc = Concilium.CreateWebClient();
            var result = wc.DownloadData("http://api.icndb.com/jokes/random?lastName=&firstName=" + target);

            dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(result));

            if (json.type == null || json.type.Value != "success")
            {
                Log.Get().Info(string.Format("Joke failed: {0}", _sSource));
                Client.LocalUser.SendMessage(Concilium.GetDefaultReplyTarget(_sSource, _sTarget), "Joke failed");
            }
            else
            {
                var joke = json.value.joke.Value as string;
                joke = joke.Replace("  ", " ");
                joke = joke.Replace(" .", ".");
                joke = joke.Replace(" ,", ",");
                joke = joke.Replace(" 's", "'s");
                joke = HttpUtility.HtmlDecode(joke);
                Log.Get().Info(string.Format("{0} wants a joke about {1}", _sSource, target));
                Client.LocalUser.SendMessage(Concilium.GetDefaultReplyTarget(_sSource, _sTarget), joke);
            }
        }
    }
}
