using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace ManuscriptEdit
{
    public partial class MainWindow : Form
    {
        FogbugzWrapper.FogbugzClient _fbw;
        public MainWindow()
        {
            InitializeComponent();            
            UpdateStats();
            lblCount.Text = $"{0:000}/{0:000}";
        }


        private FogbugzWrapper.Case[] _cases;
        private int _currentIdx = 0;
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Major Code Smell", "S125:Sections of code should not be commented out", Justification = "Sample code")]
        private void button1_Click(object sender, System.EventArgs e)
        {
            var list = new List<string>();
            foreach( var item in cbProjects.CheckedItems)
            {
                list.Add(item.ToString());
            }
            if (list.Count < 1) { MessageBox.Show("Select at least 1 project"); return; }
            var filter = 282;
            if ( int.TryParse(tbFilter.Text, out var iTemp)) { filter = iTemp; }
            _ = Task.Run(() => GetCases(list.ToArray(), Convert.ToInt32(numericYears.Value), filter));           
        }
        private void GetCases(string [] projects, int years, int filter)
        {
            SetEnabled(false);
            var cases = _fbw.GetCases(filter);
            var cutoffYear = DateTime.Now.Year - years;
            _cases = cases.Cases.Case.Where(x => projects.Contains(x.SProject) && x.DtLastUpdated.Year < cutoffYear).ToArray();
            DisplayCase(0);
            SetEnabled(true);
        }
        private void DisplayCase(int index)
        {
            if (InvokeRequired) { BeginInvoke(new Action(() => { DisplayCase(index); }));return; }
            if (index >= _cases.Length) { return; }
            _currentIdx = index;
            var c = _cases[index];
            lblCount.Text = $"{(1 + index):000}/{_cases.Count():000}";
            lblTitle.Text = $"[{c.BugIdx}] - {c.SProject} - {c.SArea} - {c.STitle} - ({c.SStatus})";
            rtbCaseDetails.Text = "";
            foreach( var sEvent in c.Events.Event)
            {
                var bHasText = !string.IsNullOrWhiteSpace(sEvent.Text);
                var bHasHTML = sEvent.SHtml is XmlNode [];
                if ( !bHasText && !bHasHTML) { continue; }
                var text = string.Empty;
                if (bHasText) { text = sEvent.Text; }
                if (bHasHTML) { text = ((XmlNode [])sEvent.SHtml)[0].Value; }
                rtbCaseDetails.AppendText($"{sEvent.SPerson} - {text}\r\n");
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("CodeQuality", "IDE0051:Remove unused private members", Justification = "SampleCode")]
        private void WriteOutProjects()
        {
            var projects = _fbw.GetProjects();
            var list = new List<string>();
            foreach (var project in projects.Projects.Project)
            {
                list.Add($"project={project.IxProject}, name={project.SProject}");
            }
            System.IO.File.WriteAllLines("projects.txt", list.ToArray());
        }
        private int _touched = 0;
        private int _skipped = 0;
        private int _closed = 0;
        private void btnTouch_Click(object sender, System.EventArgs e)
        {            
            var c = _cases[_currentIdx];
            _fbw.TouchCase(c.BugIdx);
            _touched++;
            UpdateStats();
            DisplayCase(_currentIdx + 1);
        }

        private void btnClose_Click(object sender, System.EventArgs e)
        {
            var c = _cases[_currentIdx];
            _fbw.ResolveAndClose(c.BugIdx);
            _closed++;
            UpdateStats();
            DisplayCase(_currentIdx + 1);
        }

        private void btnSkip_Click(object sender, System.EventArgs e)
        {
            _skipped++;
            UpdateStats();
            DisplayCase(_currentIdx + 1);
        }
        private void UpdateStats()
        {
            lblStats.Text = $"skipped: {_skipped}, touched: {_touched}, closed: {_closed}";
        }

        private void btnGetProjects_Click(object sender, EventArgs e)
        {
            _fbw = new FogbugzWrapper.FogbugzClient($@"http://{Properties.Settings.Default.ManuscriptServerAddress}/api.asp?", tbUser.Text, tbPassword.Text);
            _ = Task.Run(() => GetProjects());
        }
        private void GetProjects()
        {
            SetEnabled(false);
            var projectsResponse = _fbw.GetProjects();
            var list = new List<string>();
            list.AddRange(projectsResponse.Projects.Project.Select(x => x.SProject));
            SetProjects(list.ToArray());
            SetEnabled(true);
        }
        private void SetProjects(string [] projects)
        {
            if (InvokeRequired) { BeginInvoke(new Action(() => { SetProjects(projects); })); return; }
            cbProjects.Items.AddRange(projects);
        }
        private void SetEnabled(bool bEnable)
        {
            if(InvokeRequired) { BeginInvoke(new Action(() => { SetEnabled(bEnable); })); return; }
            Enabled = bEnable;
        }
    }
}
