//------------------------------------------------------------------------------
// The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at  http://www.nopCommerce.com/License.aspx. 
// 
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. 
// See the License for the specific language governing rights and limitations under the License.
// 
// The Original Code is nopCommerce.
// The Initial Developer of the Original Code is NopSolutions.
// All Rights Reserved.
// 
// Contributor(s): _______. 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using NopSolutions.NopCommerce.Common.Categories;
using NopSolutions.NopCommerce.Common.Manufacturers;
using NopSolutions.NopCommerce.Common.Media;
using NopSolutions.NopCommerce.Common.Products;
using NopSolutions.NopCommerce.Common.Products.Specs;
using NopSolutions.NopCommerce.Common.Templates;
using NopSolutions.NopCommerce.Common.Utils;
using NopSolutions.NopCommerce.Web.Administration.Modules;

namespace NopSolutions.NopCommerce.Web.Administration.Modules
{
    public partial class RelatedProductsControl : BaseNopAdministrationUserControl
    {
        [Serializable]
        private class RelatedProductHelperClass
        {
            public int RelatedProductID { get; set; }
            public int ProductID2 { get; set; }
            public string ProductInfo2 { get; set; }
            public bool IsMapped { get; set; }
            public int DisplayOrder { get; set; }
        }

        private Dictionary<int, RelatedProductHelperClass> _gridState;
        private Dictionary<int, RelatedProductHelperClass> GridState
        {
            get {
                if (_gridState == null)
                {
                    _gridState = ViewState["RelatedProductsState"] as Dictionary<int, RelatedProductHelperClass>;
                    if (_gridState == null)
                    {
                        _gridState = new Dictionary<int, RelatedProductHelperClass>();
                        ViewState["RelatedProductsState"] = _gridState;
                    }
                }
                return _gridState;
            }

            set {
                _gridState = value;
                ViewState["RelatedProductsState"] = value;
            }
        }
        
        private void UpdateState()
        {
            Dictionary<int, RelatedProductHelperClass> state = GridState;
            foreach (GridViewRow row in gvRelatedProducts.Rows)
            {
                CheckBox cbProductInfo2 = row.FindControl("cbProductInfo2") as CheckBox;
                HiddenField hfProductID2 = row.FindControl("hfProductID2") as HiddenField;
                HiddenField hfRelatedProductID = row.FindControl("hfRelatedProductID") as HiddenField;
                NumericTextBox txtRowDisplayOrder = row.FindControl("txtDisplayOrder") as NumericTextBox;
                int relatedProductID = int.Parse(hfRelatedProductID.Value);
                int productID2 = int.Parse(hfProductID2.Value);
                int displayOrder = txtRowDisplayOrder.Value;

                if (cbProductInfo2.Checked || (relatedProductID > 0))
                {
                    state[productID2] = new RelatedProductHelperClass()
                    {
                        ProductID2 = productID2,
                        RelatedProductID = relatedProductID,
                        IsMapped = cbProductInfo2.Checked,
                        DisplayOrder = displayOrder
                    };
                }
                else if (state.ContainsKey(productID2))
                {
                    state.Remove(productID2);
                }
            }
            GridState = state;
        }

        private void MapState(int Id, RelatedProductHelperClass rp)
        {
            if (GridState.ContainsKey(Id))
            {
                RelatedProductHelperClass srp = GridState[Id];
                rp.IsMapped = srp.IsMapped;
                rp.DisplayOrder = srp.DisplayOrder;
            }
        }


        private void BindData()
        {
            Product product = ProductManager.GetProductByID(this.ProductID);
            if (product != null)
            {
                RelatedProductCollection existingRelatedProductCollection = product.RelatedProducts;
                List<RelatedProductHelperClass> relatedProducts = GetRelatedProducts(existingRelatedProductCollection);
                gvRelatedProducts.DataSource = relatedProducts;
                gvRelatedProducts.DataBind();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.BindData();
            }
            else
            {
                UpdateState();
            }
        }

        public void SaveInfo()
        {
            Product product = ProductManager.GetProductByID(this.ProductID);
            if (product != null)
            {
                foreach (RelatedProductHelperClass item in GridState.Values)
                {
                    if (item.IsMapped && (item.RelatedProductID > 0))
                        ProductManager.UpdateRelatedProduct(item.RelatedProductID, product.ProductID, item.ProductID2, item.DisplayOrder);
                    else if (item.IsMapped && (item.RelatedProductID == 0))
                        ProductManager.InsertRelatedProduct(product.ProductID, item.ProductID2, item.DisplayOrder);
                    else if (!item.IsMapped && (item.RelatedProductID > 0))
                        ProductManager.DeleteRelatedProduct(item.RelatedProductID);
                }
            }
        }

        protected void gvRelatedProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvRelatedProducts.PageIndex = e.NewPageIndex;
            BindData();
        }

        public int ProductID
        {
            get
            {
                return CommonHelper.QueryStringInt("ProductID");
            }
        }

        private List<RelatedProductHelperClass> GetRelatedProducts(RelatedProductCollection ExistingRelatedProductCollection)
        {
            ProductCollection productCollection = ProductManager.GetAllProducts();
            List<RelatedProductHelperClass> result = new List<RelatedProductHelperClass>();
            for (int i = 0; i < productCollection.Count; i++)
            {
                Product product = productCollection[i];
                RelatedProduct existingRelatedProduct = ExistingRelatedProductCollection.FindRelatedProduct(this.ProductID, product.ProductID);
                RelatedProductHelperClass rp = new RelatedProductHelperClass();
                if (existingRelatedProduct != null)
                {
                    rp.RelatedProductID = existingRelatedProduct.RelatedProductID;
                    rp.IsMapped = true;
                    rp.DisplayOrder = existingRelatedProduct.DisplayOrder;
                }
                else
                {
                    rp.DisplayOrder = 1;
                }
                rp.ProductID2 = product.ProductID;
                rp.ProductInfo2 = product.Name;

                MapState(product.ProductID, rp);

                result.Add(rp);

            }

            return result;
        }
    }
}