//------------------------------------------------------------------------------
// 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.IO;
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;
using NopSolutions.NopCommerce.Common.ExportImport;
using NopSolutions.NopCommerce.Common.Media;
using NopSolutions.NopCommerce.Common.Products;
using NopSolutions.NopCommerce.Common.Products.Attributes;
using NopSolutions.NopCommerce.Common.Promo.Discounts;
using NopSolutions.NopCommerce.Common.Tax;
using NopSolutions.NopCommerce.Common.Utils;
using NopSolutions.NopCommerce.Common.Warehouses;
using NopSolutions.NopCommerce.Web.Administration.Modules;


namespace NopSolutions.NopCommerce.Web.Administration.Modules
{
    public partial class ProductVariantInfoControl : BaseNopAdministrationUserControl
    {
        private void BindData()
        {
            ProductVariant productVariant = ProductManager.GetProductVariantByID(this.ProductVariantID);
            if (productVariant != null)
            {
                Product product = productVariant.Product;
                if (product == null)
                    Response.Redirect("Products.aspx");

                this.txtName.Text = productVariant.Name;
                this.txtSKU.Text = productVariant.SKU;
                this.txtDescription.Value = productVariant.Description;
                this.txtAdminComment.Text = productVariant.AdminComment;
                this.txtManufacturerPartNumber.Text = productVariant.ManufacturerPartNumber;
                this.cbIsDownload.Checked = productVariant.IsDownload;

                Download productVariantDownload = productVariant.Download;
                if (productVariantDownload != null)
                {
                    btnRemoveProductVariantDownload.Visible = true;
                    hlProductVariantDownload.Visible = true;
                    string adminDownloadUrl = DownloadManager.GetAdminDownloadUrl(productVariantDownload);
                    hlProductVariantDownload.NavigateUrl = adminDownloadUrl;
                }
                else
                {
                    btnRemoveProductVariantDownload.Visible = false;
                    hlProductVariantDownload.Visible = false;
                }
                this.cbIsShipEnabled.Checked = productVariant.IsShipEnabled;
                this.cbIsFreeShipping.Checked = productVariant.IsFreeShipping;
                this.txtAdditionalShippingCharge.Value = productVariant.AdditionalShippingCharge;
                this.cbIsTaxExempt.Checked = productVariant.IsTaxExempt;
                CommonHelper.SelectListItem(this.ddlTaxCategory, productVariant.TaxCategoryID);
                this.cbManageStock.Checked = productVariant.ManageInventory;
                this.txtStockQuantity.Value = productVariant.StockQuantity;
                this.txtMinStockQuantity.Value = productVariant.MinStockQuantity;
                CommonHelper.SelectListItem(this.ddlLowStockActivity, productVariant.LowStockActivityID);
                this.txtNotifyForQuantityBelow.Value = productVariant.NotifyAdminForQuantityBelow;
                this.txtOrderMinimumQuantity.Value = productVariant.OrderMinimumQuantity;
                this.txtOrderMaximumQuantity.Value = productVariant.OrderMaximumQuantity;
                CommonHelper.SelectListItem(this.ddlWarehouse, productVariant.WarehouseId);
                this.cbDisableBuyButton.Checked = productVariant.DisableBuyButton;
                this.cbRequiresTextOption.Checked = productVariant.RequiresTextOption;
                this.txtTextOptionPrompt.Text = productVariant.TextOptionPrompt;
                this.txtPrice.Value = productVariant.Price;
                this.txtOldPrice.Value = productVariant.OldPrice;
                this.txtWeight.Value = productVariant.Weight;
                this.txtLength.Value = productVariant.Length;
                this.txtWidth.Value = productVariant.Width;
                this.txtHeight.Value = productVariant.Height;

                Picture productVariantPicture = productVariant.Picture;
                btnRemoveProductVariantImage.Visible = productVariantPicture != null;
                string pictureUrl = PictureManager.GetPictureUrl(productVariantPicture, 100);
                this.iProductVariantPicture.Visible = true;
                this.iProductVariantPicture.ImageUrl = pictureUrl;

                if (productVariant.AvailableStartDateTime.HasValue)
                {
                    this.cAvailableStartDateTimeButtonExtender.SelectedDate = productVariant.AvailableStartDateTime.Value;
                }
                if (productVariant.AvailableEndDateTime.HasValue)
                {
                    this.cAvailableEndDateTimeButtonExtender.SelectedDate = productVariant.AvailableEndDateTime.Value;
                }

                this.cbPublished.Checked = productVariant.Published;
                this.txtDisplayOrder.Value = productVariant.DisplayOrder;
            }
            else
            {
                btnRemoveProductVariantDownload.Visible = false;
                hlProductVariantDownload.Visible = false;

                this.btnRemoveProductVariantImage.Visible = false;
                this.iProductVariantPicture.Visible = false;

                Product product = ProductManager.GetProductByID(this.ProductID);
                if (product == null)
                    Response.Redirect("Products.aspx");
            }
        }

        private void FillDropDowns()
        {
            this.ddlTaxCategory.Items.Clear();
            ListItem itemTaxCategory = new ListItem("---", "0");
            this.ddlTaxCategory.Items.Add(itemTaxCategory);
            TaxCategoryCollection taxCategoryCollection = TaxCategoryManager.GetAllTaxCategories();
            foreach (TaxCategory taxCategory in taxCategoryCollection)
            {
                ListItem item2 = new ListItem(taxCategory.Name, taxCategory.TaxCategoryID.ToString());
                this.ddlTaxCategory.Items.Add(item2);
            }

            this.ddlWarehouse.Items.Clear();
            ListItem itemWarehouse = new ListItem("---", "0");
            this.ddlWarehouse.Items.Add(itemWarehouse);
            WarehouseCollection warehouseCollection = WarehouseManager.GetAllWarehouses();
            foreach (Warehouse warehouse in warehouseCollection)
            {
                ListItem item2 = new ListItem(warehouse.Name, warehouse.WarehouseID.ToString());
                this.ddlWarehouse.Items.Add(item2);
            }

            CommonHelper.FillDropDownWithEnum(this.ddlLowStockActivity, typeof(LowStockActivityEnum));
        }

        private void TogglePanels()
        {
            pnlDownloadFile.Visible = cbIsDownload.Checked;
            pnlStockQuantity.Visible = cbManageStock.Checked;
            pnlMinStockQuantity.Visible = cbManageStock.Checked;
            pnlLowStockActivity.Visible = cbManageStock.Checked;
            pnlNotifyForQuantityBelow.Visible = cbManageStock.Checked;
        }

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

        protected void cbManageStock_CheckedChanged(object sender, EventArgs e)
        {
            this.TogglePanels();
        }

        protected void cbIsDownload_CheckedChanged(object sender, EventArgs e)
        {
            this.TogglePanels();
        }

        public ProductVariant SaveInfo()
        {
            ProductVariant productVariant = ProductManager.GetProductVariantByID(ProductVariantID);

            DateTime? availableStartDateTime = null;
            DateTime? availableEndDateTime = null;
            DateTime availableStartDateTimeTmp = DateTime.Now;
            if (DateTime.TryParse(txtAvailableStartDateTime.Text, out availableStartDateTimeTmp))
            {
                availableStartDateTime = DateTime.SpecifyKind(availableStartDateTimeTmp, DateTimeKind.Utc);
            }
            DateTime availableEndDateTimeTmp = DateTime.Now;
            if (DateTime.TryParse(txtAvailableEndDateTime.Text, out availableEndDateTimeTmp))
            {
                availableEndDateTime = DateTime.SpecifyKind(availableEndDateTimeTmp, DateTimeKind.Utc);
            }

            if (productVariant != null)
            {
                Picture productVariantPicture = productVariant.Picture;
                HttpPostedFile productVariantPictureFile = fuProductVariantPicture.PostedFile;
                if ((productVariantPictureFile != null) && (!String.IsNullOrEmpty(productVariantPictureFile.FileName)))
                {
                    byte[] productVariantPictureBinary = PictureManager.GetPictureBits(productVariantPictureFile.InputStream, productVariantPictureFile.ContentLength);
                    if (productVariantPicture != null)
                        productVariantPicture = PictureManager.UpdatePicture(productVariantPicture.PictureID, productVariantPictureBinary, productVariantPictureFile.ContentType, true);
                    else
                        productVariantPicture = PictureManager.InsertPicture(productVariantPictureBinary, productVariantPictureFile.ContentType, true);
                }
                int productVariantPictureID = 0;
                if (productVariantPicture != null)
                    productVariantPictureID = productVariantPicture.PictureID;

                Download productVariantDownload = productVariant.Download;
                HttpPostedFile productVariantDownloadFile = fuProductVariantDownload.PostedFile;
                if ((productVariantDownloadFile != null) && (!String.IsNullOrEmpty(productVariantDownloadFile.FileName)))
                {
                    byte[] productVariantDownloadBinary = DownloadManager.GetDownloadBits(productVariantDownloadFile.InputStream, productVariantDownloadFile.ContentLength);
                    if (productVariantDownload != null)
                        productVariantDownload = DownloadManager.UpdateDownload(productVariantDownload.DownloadID, productVariantDownloadBinary, productVariantDownloadFile.ContentType, Path.GetExtension(productVariantDownloadFile.FileName), true);
                    else
                        productVariantDownload = DownloadManager.InsertDownload(productVariantDownloadBinary, productVariantDownloadFile.ContentType, Path.GetExtension(productVariantDownloadFile.FileName), true);
                }
                int productVariantDownloadID = 0;
                if (productVariantDownload != null)
                    productVariantDownloadID = productVariantDownload.DownloadID;

                LowStockActivityEnum lowStockActivity = (LowStockActivityEnum)Enum.ToObject(typeof(LowStockActivityEnum), int.Parse(this.ddlLowStockActivity.SelectedItem.Value));

                productVariant = ProductManager.UpdateProductVariant(ProductVariantID, productVariant.ProductID,
                     txtName.Text, txtSKU.Text, txtDescription.Value, txtAdminComment.Text, txtManufacturerPartNumber.Text,
                     cbIsDownload.Checked, productVariantDownloadID, cbIsShipEnabled.Checked,
                     cbIsFreeShipping.Checked, txtAdditionalShippingCharge.Value,
                     cbIsTaxExempt.Checked, int.Parse(this.ddlTaxCategory.SelectedItem.Value),
                     cbManageStock.Checked, txtStockQuantity.Value,
                     txtMinStockQuantity.Value, lowStockActivity, txtNotifyForQuantityBelow.Value,
                     txtOrderMinimumQuantity.Value, txtOrderMaximumQuantity.Value,
                     int.Parse(this.ddlWarehouse.SelectedItem.Value), cbDisableBuyButton.Checked,
                     cbRequiresTextOption.Checked, txtTextOptionPrompt.Text,
                     txtPrice.Value, txtOldPrice.Value, txtWeight.Value, txtLength.Value,
                     txtWidth.Value, txtHeight.Value, productVariantPictureID,
                     availableStartDateTime, availableEndDateTime, cbPublished.Checked,
                     productVariant.Deleted, txtDisplayOrder.Value, productVariant.CreatedOn, DateTime.Now);
            }
            else
            {
                Product product = ProductManager.GetProductByID(this.ProductID);
                if (product != null)
                {
                    Picture productVariantPicture = null;
                    HttpPostedFile productVariantPictureFile = fuProductVariantPicture.PostedFile;
                    if ((productVariantPictureFile != null) && (!String.IsNullOrEmpty(productVariantPictureFile.FileName)))
                    {
                        byte[] productVariantPictureBinary = PictureManager.GetPictureBits(productVariantPictureFile.InputStream, productVariantPictureFile.ContentLength);
                        productVariantPicture = PictureManager.InsertPicture(productVariantPictureBinary, productVariantPictureFile.ContentType, true);
                    }
                    int productVariantPictureID = 0;
                    if (productVariantPicture != null)
                        productVariantPictureID = productVariantPicture.PictureID;

                    Download productVariantDownload = null;
                    HttpPostedFile productVariantDownloadFile = fuProductVariantDownload.PostedFile;
                    if ((productVariantDownloadFile != null) && (!String.IsNullOrEmpty(productVariantDownloadFile.FileName)))
                    {
                        byte[] productVariantDownloadBinary = DownloadManager.GetDownloadBits(productVariantDownloadFile.InputStream, productVariantDownloadFile.ContentLength);
                        productVariantDownload = DownloadManager.InsertDownload(productVariantDownloadBinary, productVariantDownloadFile.ContentType, Path.GetExtension(productVariantDownloadFile.FileName), true);
                    }
                    int productVariantDownloadID = 0;
                    if (productVariantDownload != null)
                        productVariantDownloadID = productVariantDownload.DownloadID;

                    DateTime nowDT = DateTime.Now;
                    LowStockActivityEnum lowStockActivity = (LowStockActivityEnum)Enum.ToObject(typeof(LowStockActivityEnum), int.Parse(this.ddlLowStockActivity.SelectedItem.Value));
                    productVariant = ProductManager.InsertProductVariant(product.ProductID,
                         txtName.Text, txtSKU.Text, txtDescription.Value, txtAdminComment.Text, txtManufacturerPartNumber.Text,
                         cbIsDownload.Checked, productVariantDownloadID, cbIsShipEnabled.Checked,
                         cbIsFreeShipping.Checked, txtAdditionalShippingCharge.Value,
                         cbIsTaxExempt.Checked, int.Parse(this.ddlTaxCategory.SelectedItem.Value),
                         cbManageStock.Checked, txtStockQuantity.Value,
                         txtMinStockQuantity.Value, lowStockActivity, txtNotifyForQuantityBelow.Value,
                         txtOrderMinimumQuantity.Value, txtOrderMaximumQuantity.Value,
                         int.Parse(this.ddlWarehouse.SelectedItem.Value), cbDisableBuyButton.Checked,
                         cbRequiresTextOption.Checked, txtTextOptionPrompt.Text,
                         txtPrice.Value, txtOldPrice.Value, txtWeight.Value, txtLength.Value,
                         txtWidth.Value, txtHeight.Value, productVariantPictureID,
                         availableStartDateTime, availableEndDateTime, cbPublished.Checked,
                         false, txtDisplayOrder.Value, nowDT, nowDT);
                }
                else
                {
                    Response.Redirect("Products.aspx");
                }
            }
            return productVariant;
        }

        protected void btnRemoveProductVariantImage_Click(object sender, EventArgs e)
        {
            try
            {
                ProductVariant productVariant = ProductManager.GetProductVariantByID(this.ProductVariantID);
                if (productVariant != null)
                {
                    PictureManager.DeletePicture(productVariant.PictureID);
                    ProductManager.RemoveProductVariantPicture(productVariant.ProductVariantID);
                    BindData();
                }
            }
            catch (Exception exc)
            {
                ProcessException(exc);
            }
        }

        protected void btnRemoveProductVariantDownload_Click(object sender, EventArgs e)
        {
            try
            {
                ProductVariant productVariant = ProductManager.GetProductVariantByID(this.ProductVariantID);
                if (productVariant != null)
                {
                    DownloadManager.DeleteDownload(productVariant.DownloadID);
                    ProductManager.RemoveProductVariantDownload(productVariant.ProductVariantID);
                    BindData();
                }
            }
            catch (Exception exc)
            {
                ProcessException(exc);
            }
        }

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

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