using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Telerik.WinControls.UI;

namespace SM64_ROM_Manager.ProgressUpdater
{
    public partial class PasteFromDocument : RadForm
    {
        private Settings settings;

        public Image DocumentImage { get; private set; }

        public PasteFromDocument(Settings settings)
        {
            this.settings = settings;
            InitializeComponent();
        }

        private void ButtonX_Paste_Click(object sender, EventArgs e)
        {
            RadListDataItem selectedItem = null;
            foreach (RadListDataItem item in RadListControl_Paragraph.Items)
            {
                if (selectedItem == null && item.Selected)
                    selectedItem = item;
            }

            if (selectedItem?.Tag is object)
            {
                var md = (string)selectedItem.Tag;
                DocumentImage = MarkdownHelper.GetAsImage(md);
                DialogResult = DialogResult.OK;
            }
        }

        private async void textBoxX1_TextChanged(object sender, EventArgs e)
        {
            var url = radTextBoxControl1.Text.Trim();
            settings.UpcommingVersionsDownloadURL = url;
            if (!string.IsNullOrEmpty(url))
                await GetNewItems(url);
        }

        private async Task GetNewItems(string url)
        {
            var mdDocStr = await DownloadString(url);
            if (!string.IsNullOrEmpty(mdDocStr))
            {
                RadListControl_Paragraph.BeginUpdate();
                RadListControl_Paragraph.Items.Clear();

                foreach (var kvp in MarkdownHelper.SplitToVersions(mdDocStr))
                {
                    var item = new RadListDataItem
                    {
                        Text = kvp.Key,
                        Tag = kvp.Value
                    };

                    RadListControl_Paragraph.Items.Add(item);
                }

                RadListControl_Paragraph.EndUpdate();
                RadListControl_Paragraph.Refresh();

                if (RadListControl_Paragraph.Items.Any())
                    RadListControl_Paragraph.Items[0].Selected = true;
            }
        }

        private static async Task<string> DownloadString(string url)
        {
            var wc = new HttpClient();
            var res = await wc.GetStringAsync(url);
            wc.Dispose();
            return res;
        }

        private void PasteFromDocument_Load(object sender, EventArgs e)
        {
            radTextBoxControl1.Text = settings.UpcommingVersionsDownloadURL;
        }
    }
}
