using System;
using System.Linq;
using System.Windows.Forms;
using Tanshu.Accounts.Entities;
using Tanshu.Accounts.Repository;
using System.Collections.Generic;
using Tanshu.Accounts.Entities.Auth;

namespace Tanshu.Accounts.PointOfSale
{
    public partial class UserListForm : Form
    {
        private IList<User> _list;
        public UserListForm()
        {
            InitializeComponent();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            using (var frm = new UserForm(null))
                frm.ShowDialog();
            using (var bi = new UserBI())
                _list = bi.List();
            bsList.DataSource = _list;
        }

        private void UserListForm_Load(object sender, EventArgs e)
        {
            ShowGrid();
        }
        private void ShowGrid()
        {
            using (var bi = new UserBI())
                _list = bi.List();
            bsList.DataSource = _list;
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            var id = ((User)bsList.Current).UserID;
            using (var frm = new UserForm(id))
                frm.ShowDialog();
            using (var bi = new UserBI())
                _list = bi.List();
            bsList.DataSource = _list;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dgvUsers_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            var data = dgvUsers.Rows[e.RowIndex].DataBoundItem as User;
            if (data == null)
                return;
            if (e.ColumnIndex == dgvUsers.Columns["Password"].Index)
            {
                e.Value = "******";
            }

            if (e.ColumnIndex == dgvUsers.Columns["MsrString"].Index)
            {
                e.Value = !string.IsNullOrEmpty(data.MsrString);
            }

            if (e.ColumnIndex == dgvUsers.Columns["UserGroups"].Index)
            {
                e.Value = string.Join(", ", data.UserGroups.Select(x => x.Group.Name).ToArray());
            }

            var tax = e.Value as Tax;
            if (tax != null)
            {
                e.Value = string.Format("{1:P} - {0}", tax.Name, tax.Rate); ;
                return;
            }
            var productGroup = e.Value as ProductGroup;
            if (productGroup != null)
            {
                e.Value = productGroup.Name;
            }
        }
        private void chkIsActive_CheckStateChanged(object sender, EventArgs e)
        {
            ShowGrid();
        }
    }
}