using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Services.Client;
using TelerikStore.EbayService;
using Telerik.Web.UI;
using TelerikStore.MasterPages;

namespace TelerikStore.Views
{
    public partial class ProductList_ListView : System.Web.UI.UserControl
    {
        private static EBayData ebayContext;

        private static readonly String ebayString = "http://ebayodata.cloudapp.net";

        //Public property to use with our CategoryID
        public String CategoryID { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            ebayContext = new EBayData(new Uri(ebayString));
        }

        protected void BuyButton_Click(object sender, CommandEventArgs e)
        {
            CategoryView1 parentPage = (CategoryView1)this.Page;
            TwoColumn masterPage = (TwoColumn)parentPage.Master;

            Label priceTotalLabel = (Label)masterPage.FindControl("PriceTotalLabel");
            Label itemsTotalLabel = (Label)masterPage.FindControl("ItemsTotalLabel");

            int currentTotalItems = Convert.ToInt16(itemsTotalLabel.Text);
            currentTotalItems++;
            itemsTotalLabel.Text = currentTotalItems.ToString();

            double currentPriceTotal = Convert.ToDouble(priceTotalLabel.Text);
            currentPriceTotal += Convert.ToDouble(e.CommandArgument);
            priceTotalLabel.Text = currentPriceTotal.ToString();

            HttpContext.Current.Cache["PriceTotal"] = currentPriceTotal;
            HttpContext.Current.Cache["ItemsTotal"] = currentTotalItems;

        }

        protected void ProductListView_NeedDataSource(object sender, RadListViewNeedDataSourceEventArgs e)
        {
            if (Session["Products"] == null)
            {
                List<Item> allItems = GetCategoryItems();
                ProductListView.DataSource = allItems;
                Session["Products"] = allItems;
            }
            else
            {
                ProductListView.DataSource = Session["Products"] as List<Item>;
            }
        }

        private List<Item> GetCategoryItems()
        {
            List<Item> listToReturn = new List<Item>();

            string category = CategoryID;

            if (category != null)
            {
                string categorySearchString = String.Format("Items?$filter=PrimaryCategoryId%20eq%20'{0}'", category);

                listToReturn = ebayContext.Execute<Item>(new Uri(categorySearchString, UriKind.Relative)).ToList();
            }

            return listToReturn;
        }
    }
}