﻿using System;
using System.Windows.Forms;

namespace EAValidator.Controls
{
    internal class SortableListview : ListView
    {
        private readonly ListViewColumnSorter sorter = new ListViewColumnSorter();

        public SortableListview()
        {
            ListViewItemSorter = sorter;
        }

        protected override void OnColumnClick(ColumnClickEventArgs e)
        {
            // Determine if clicked column is already the column that is being sorted.
            if (e.Column == sorter.SortColumn)
            {
                // Reverse the current sort direction for this column.
                sorter.Order = sorter.Order == SortOrder.Ascending ? SortOrder.Descending : SortOrder.Ascending;
            }
            else
            {
                // Set the column number that is to be sorted; default to ascending.
                sorter.SortColumn = e.Column;
                sorter.Order = SortOrder.Ascending;
            }

            // Perform the sort with these new sort options.
            Sort();

        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.A)
                SelectAll();

            base.OnKeyDown(e);
        }

        private void SelectAll()
        {
            Cursor = Cursors.WaitCursor;

            foreach (ListViewItem item in Items)
            {
                item.Selected = true;
            }
            Cursor = Cursors.Default;
        }

        protected override void OnResize(EventArgs e)
        {
            int width = Width;
            int lastColumnIndex = Columns.Count - 1;

            foreach (ColumnHeader col in Columns)
            {
                if (col.Index != lastColumnIndex) width -= col.Width;
            }

            Columns[lastColumnIndex].Width = width;

            base.OnResize(e);
        }
    }
}