using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using Hitsuji.Framework.Utils;

namespace PostCardHitsuji.Utils.WinControlAttacher
{
    public class ListViewAttacher
    {
        public static void addLargeItem(ListView listView,
           System.Drawing.Image image,
           int imageWidth,
           int imageHeight,
           string text)
        {
            if (image.PixelFormat == System.Drawing.Imaging.PixelFormat.Undefined)
                return;
            try
            {
                var img = ReSizeImageUtil.reSizeImage(image, imageWidth, imageHeight);
                if (listView.LargeImageList == null)
                {
                    listView.LargeImageList = new ImageList();
                    listView.Margin = new System.Windows.Forms.Padding(0);
                    listView.LargeImageList.ImageSize = new Size(imageWidth, imageWidth);
                }

                var index = listView.Items.Count;
                listView.LargeImageList.Images.Add(img);
                listView.Items.Add(text, index);

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static void removeItem(ListView listView)
        {
            //非選択アイテムを取得
            List<KeyValuePair<string, Image>> itemList
                = new List<KeyValuePair<string, Image>>();
            int imageIndex = 0;
            foreach (ListViewItem item in listView.Items)
            {
                //選択されたアイテムを除くアイテム（ファイル名、イメージ）を一時リストに登録
                if (!item.Selected)
                    itemList.Add(new KeyValuePair<string, Image>(item.Text, listView.LargeImageList.Images[imageIndex]));
                imageIndex += 1;
            }

            //アイテムを全てクリア
            int defaultImageSizeWidth = listView.LargeImageList.ImageSize.Width;
            int defaultImageSizeHeight = listView.LargeImageList.ImageSize.Height;
            listView.Items.Clear();
            listView.LargeImageList.Images.Clear();
            listView.LargeImageList.Dispose();
            listView.LargeImageList = null;

            //前段で取得した非選択アイテムをリストビューに追加
            listView.LargeImageList = new ImageList();
            listView.LargeImageList.ImageSize = new Size(defaultImageSizeWidth, defaultImageSizeHeight);
            //int addItemIndex = 0;
            foreach (KeyValuePair<string, Image> kvp in itemList)
            {
                listView.LargeImageList.Images.Add(kvp.Value);
                listView.Items.Add(kvp.Key, listView.Items.Count);
                //    addItemIndex++;
            }
        }

    }
}
