using System;
using System.Linq;
using Products.Helpers;
using Starcounter;

namespace Products
{
    partial class ProductListPage : Json
    {
        public Action ConfirmAction = null;

        public void RefreshProducts()
        {
            this.Products.Data = Db.SQL($"SELECT p FROM {typeof(Product)} p");
        }

        [ProductListPage_json.Products]
        partial class ProductItem : Json, IBound<Product>
        {
            protected override void OnData()
            {
                base.OnData();

                this.AllSuppliers = string.Join(", ", this.Data.Suppliers.Where(x => x.Supplier != null).Select(x => x.Supplier.Name).ToArray());
                this.EditUrl = $"/products/product/{this.Data.GetObjectID()}";
            }

            void Handle(Input.Delete Action)
            {
                this.ParentPage.Confirm.Message = "Are you sure want to delete product [" + this.Name + "]?";
                this.ParentPage.ConfirmAction = () =>
                {
                    Helpers.Products provider = new Helpers.Products();

                    Db.Transact(() =>
                    {
                        provider.Delete(this.Data);
                        this.ParentPage.RefreshProducts();
                    });
                };
            }

            public ProductListPage ParentPage
            {
                get
                {
                    return this.Parent.Parent as ProductListPage;
                }
            }
        }

        [ProductListPage_json.Confirm]
        partial class PersonsConfirmPage : Json
        {
            void Cancel()
            {
                this.ParentPage.Confirm.Message = null;
                this.ParentPage.ConfirmAction = null;
            }

            void Handle(Input.Reject Action)
            {
                Cancel();
            }

            void Handle(Input.Ok Action)
            {
                if (this.ParentPage.ConfirmAction != null)
                {
                    this.ParentPage.ConfirmAction();
                }

                Cancel();
            }

            public ProductListPage ParentPage
            {
                get
                {
                    return this.Parent as ProductListPage;
                }
            }
        }
    }
}
