using System;
using System.Linq;
using System.Xml;

namespace FogbugzWrapper
{
    public class FBEvent
    {
        public enum FBStatuses
        {
            UNKNOWN,
            Opened,
            Resolved,
            Closed,
            Reactivated
        }

        public string User { get; set; }
        public string Comment { get; set; }
        public string StatusString { get; set; }
        public string TimeStamp { get; set; }
        public string ReleaseNote { get; set; }

        public int ZendeskNumber { get; set; }

        public FBEvent()
        {
        }

        public FBEvent(string dt, string sVerb, string s, string sPerson)
        {
            TimeStamp = dt;
            Comment = s;
            StatusString = sVerb;
            User = sPerson;
            UpdateStatus();
        }

        public FBEvent(XmlNode eventNode)
        {
            TimeStamp = eventNode.SelectSingleNode("dt").InnerText;
            Comment = eventNode.SelectSingleNode("s").InnerText;
            User = eventNode.SelectSingleNode("sPerson").InnerText;
            StatusString = eventNode.SelectSingleNode("sVerb").InnerText;
            if (StatusString == "ReleaseNoted")
            {
                var rNote = eventNode.SelectSingleNode("sChanges").InnerText;
                if (rNote.ToLower() != "<IGNORE>".ToLower())
                {
                    ReleaseNote = rNote;
                }
            }
            if(StatusString=="sZendesk")
            {
                if (int.TryParse(eventNode.SelectSingleNode("sChanges").InnerText, out int zendeskNumber))
                {
                    ZendeskNumber = zendeskNumber;
                }
            }
            UpdateStatus();
        }

        private void UpdateStatus()
        {
            var fBStatuses = Enum.GetValues(typeof(FBStatuses)).Cast<FBStatuses>().ToArray();
            foreach (var s in fBStatuses)
            {
                if (StatusString.StartsWith(s.ToString()))
                {
                    Status = s;
                }
            }
        }

        public FBStatuses Status { get; set; }
    }
}