using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Azyobuzi.Twirunrun
{
    public partial class NotifyForm : Form
    {
        private NotifyForm()
        {
            InitializeComponent();
        }

        public static void ShowItems(IEnumerable<StatusInfo> items, Form owner)
        {
            Point lastLocation = Point.Empty;
            const int space = 5;
            items.Reverse().ForEach(item =>
            {
                var f = new NotifyForm();
                f.Owner = owner;
                f.SetText(item);
                if (lastLocation.IsEmpty)
                {
                    var workingArea = Screen.GetWorkingArea(f);
                    lastLocation = new Point(workingArea.Right - space - f.Width, workingArea.Bottom - space - f.Height);
                }
                else
                {
                    lastLocation.Offset(0, -space - f.Height);
                    if (lastLocation.Y < 0)
                    {
                        lastLocation.X -= space + f.Width;
                        lastLocation.Y = Screen.GetWorkingArea(f).Bottom - space - f.Height;
                    }
                }
                f.Location = lastLocation;
                f.Show();
            });
            owner.Activate();
        }

        private void SetText(StatusInfo item)
        {
            profileImg.Tag = item.ProfileImageUri;
            nameLabel.Text = Settings.Instance.NameType == NameTypes.Name ? item.User.Name : item.User.Identifier.ScreenName;
            contentBox.Text = item.Text;
            closeTimer.Interval = Settings.Instance.NotifyFormShowTime * 1000;
        }

        private void closeTimer_Tick(object sender, EventArgs e)
        {
            closeTimer.Stop();
            this.Close();
        }

        private void NotifyForm_Load(object sender, EventArgs e)
        {
            var img = Icons.GetItem(profileImg.Tag.ToString());
            if (img == null)
            {
                var t = new Thread(uri =>
                {
                    var result = Icons.AddSync(uri.ToString());
                    profileImg.Invoke((MethodInvoker)(() => profileImg.Image = result));
                });
                t.IsBackground = true;
                t.Start(profileImg.Tag);
            }
            else
            {
                profileImg.Image = img;
            }
            closeTimer.Start();
        }
    }
}
