using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Data.SqlClient;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.Globalization;


/* =====================================================================

  File:      CheckOut.aspx.cs for Adventure Works Cycles Storefront Sample
  Summary:   Allows the user to review the shopping cart, and places an order if the user presses the submit button.
  Date:	     June 16, 2003

---------------------------------------------------------------------

  This file is part of the Microsoft SQL Server Code Samples.
  Copyright (C) Microsoft Corporation.  All rights reserved.

This source code is intended only as a supplement to Microsoft
Development Tools and/or on-line documentation.  See these other
materials for detailed information regarding Microsoft code samples.

THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.

======================================================= */


namespace Microsoft.Samples.SqlServer
{
	/// <summary>
	/// Summary description for CheckOut2.
	/// </summary>
    public partial class CheckOut : System.Web.UI.Page
	{
		CustomerAddresses defaultAddresses;

		//*******************************************************
		//
		// The Page_Load event on this page is used to load the
		// ShoppingCart DataGrid *the first time* the page is
		// accessed.
		//
		// Note that subsequent postbacks to the page *do not*
		// reload the Datagrid.  Instead, we rely on the control's
		// built-in viewstate management to rebuild the control
		// on the server.
		//
		//*******************************************************
		private void Page_Load(object sender, System.EventArgs e)
		{
			// Put user code to initialize the page here
			if (Page.IsPostBack == false)
			{
				// Calculate end-user's shopping cart ID
				ShoppingCartDB cart = new ShoppingCartDB();
				String cartId = cart.GetShoppingCartId();

				// Populate datagrid with shopping cart data
				MyDataGrid.DataSource = cart.GetItems(cartId);
				MyDataGrid.DataBind();

				// Update total price label
				TotalLabel.Text = cart.GetTotal(cartId);

				OrdersDB ordersDatabase = new OrdersDB();

				ShippingDropDownList.DataSource = ordersDatabase.
												  GetShippingMethods();
				ShippingDropDownList.DataTextField = "Name";
				ShippingDropDownList.DataValueField = "ShipMethodID";
				ShippingDropDownList.DataBind();

				CustomersDB customerDatabase = new CustomersDB();
				DataTable allStateProvince = customerDatabase.
											 GetAllStateProvince();

				SetupStateProvinceDropDown(
					BillToAddressStateProvinceDropDownList, allStateProvince);
				SetupStateProvinceDropDown(
					ShipToAddressStateProvinceDropDownList, allStateProvince);
				AddressControls shipToAddressControls = GatherShipToAddressControls();
				AddressControls billToAddressControls = GatherBillToAddressControls();
				defaultAddresses =
				customerDatabase.GetCustomerDefaultAddresses(Int32.
																				Parse(
					cartId, CultureInfo.InvariantCulture));
				billToAddressControls.FillControls(defaultAddresses.
												   BillingAddress);
				shipToAddressControls.FillControls(defaultAddresses.
												   ShippingAddress);
			}
		}

		private AddressControls GatherShipToAddressControls()
		{
			return new AddressControls(ShipToAddressLine1TextBox,
								ShipToAddressLine2TextBox,
								ShipToAddressCityTextBox,
								ShipToAddressStateProvinceDropDownList,
								ShipToAddressPostalCodeTextBox);
		}

		private AddressControls GatherBillToAddressControls()
		{
			return new AddressControls(
					BillToAddressLine1TextBox, BillToAddressLine2TextBox,
					BillToAddressCityTextBox,
					BillToAddressStateProvinceDropDownList,
					BillToAddressPostalCodeTextBox);
		}

		private void SetupStateProvinceDropDown(DropDownList
			stateProvinceDropDownList, DataTable allStateProvince)
		{
			stateProvinceDropDownList.DataSource = allStateProvince;
			stateProvinceDropDownList.DataTextField = "Name";
			stateProvinceDropDownList.DataValueField = "StateProvinceID";
			stateProvinceDropDownList.DataBind();
		}

		/// <summary>
		///		Copy text from the billing address to the shipping address if they are the same
		///		and the billing address changes.
		/// </summary>
		/// <param name="sender">The text box which has changed in the billing address</param>
		/// <param name="e">Ignored</param>
        protected void BillingAddressTextBox_TextChanged(object sender,
													   EventArgs e)
		{
			if (ShipSameAsBillCheckBox.Checked)
			{
				TextBox source = (TextBox)sender;
				TextBox destination;

				switch (source.ID)
				{
					case "BillToAddressLine1TextBox": destination =
													  ShipToAddressLine1TextBox;
						break;

					case "BillToAddressLine2TextBox": destination =
													  ShipToAddressLine2TextBox;
						break;

					case "BillToAddressCityTextBox": destination =
													 ShipToAddressCityTextBox;
						break;

					case "BillToAddressPostalCodeTextBox": destination =
														   ShipToAddressPostalCodeTextBox;
						break;

					default:
						destination = null;
						break;
				}
				if (destination != null)
					destination.Text = source.Text;
			}
		}

        protected void BillingAddressDropDownList_SelectedIndexChanged(object
			sender, EventArgs e)
		{
			if (ShipSameAsBillCheckBox.Checked)
			{
				ShipToAddressStateProvinceDropDownList.SelectedIndex =
				BillToAddressStateProvinceDropDownList.
																	   SelectedIndex;
			}
		}

        protected void ShipSameAsBillCheckBox_CheckedChanged(object sender,
														   EventArgs e)
		{
			if (ShipSameAsBillCheckBox.Checked)
			{
				ShipToAddressLine1TextBox.Enabled = false;
				ShipToAddressLine1TextBox.Text = BillToAddressLine1TextBox.Text;
				ShipToAddressLine2TextBox.Enabled = false;
				ShipToAddressLine2TextBox.Text = BillToAddressLine2TextBox.Text;
				ShipToAddressCityTextBox.Enabled = false;
				ShipToAddressCityTextBox.Text = BillToAddressCityTextBox.Text;
				ShipToAddressStateProvinceDropDownList.Enabled = false;
				ShipToAddressStateProvinceDropDownList.SelectedIndex =
				BillToAddressStateProvinceDropDownList.
																	   SelectedIndex;
				ShipToAddressPostalCodeTextBox.Enabled = false;
				ShipToAddressPostalCodeTextBox.Text =
				BillToAddressPostalCodeTextBox.
													  Text;
			}
			else
			{
				ShipToAddressLine1TextBox.Enabled = true;
				ShipToAddressLine2TextBox.Enabled = true;
				ShipToAddressCityTextBox.Enabled = true;
				ShipToAddressStateProvinceDropDownList.Enabled = true;
				ShipToAddressPostalCodeTextBox.Enabled = true;
			}
		}

		//*******************************************************
		//
		// The SubmitButton_Click event handle is used to order the
		// items within the current shopping cart.  It then
		// displays the orderid and order status to the screen
		// (hiding the "SubmitButton" button to ensure that the
		// user can't click it twice).
		//
		//*******************************************************
		protected void SubmitButton_Click(object sender,
										System.Web.UI.ImageClickEventArgs e)
		{
			ShoppingCartDB cart = new ShoppingCartDB();

			// Calculate end-user's shopping cart ID
			String cartId = cart.GetShoppingCartId();

			// Calculate end-user's customerID
			String customerId = User.Identity.Name;
			bool isExtendedProcessing =
				 (ConfigurationSettings.AppSettings["ExtendedOrderProcessing"].
										 ToUpper(WorldReady.USCulture) ==
										 "TRUE");

			if ((cartId != null) && (customerId != null))
			{
				AddressControls shipToAddressControls =
								GatherShipToAddressControls();
				AddressControls billToAddressControls =
								GatherBillToAddressControls();

				CustomersDB customerDatabase = new CustomersDB();
				int customerIDNumber = Int32.Parse(customerId);
				int billToAddressID = customerDatabase.AccessCustomerAddress(
					customerIDNumber, "Billing",
					billToAddressControls.GetCustomerAddress());
				int shipToAddressID = customerDatabase.AccessCustomerAddress(
					customerIDNumber, "Shipping",
					shipToAddressControls.GetCustomerAddress());

				// Place the order.  If we're using extended processing, start at the initial state, otherwise
				// just indicate that the order has been shipped.
				OrdersDB ordersDatabase = new OrdersDB();
				int orderId = ordersDatabase.PlaceOrder(customerId, cartId,
														Int32.Parse(
					ShippingDropDownList.SelectedValue,
					CultureInfo.InvariantCulture),
														isExtendedProcessing ?
														Constants.Status.
														PendingInventoryCheck :
														Constants.Status.
														Shipped,
														billToAddressID,
														shipToAddressID);

				// Demonstrate service broker features if ExtendedOrderProcessing is true in web.config file.
				if (isExtendedProcessing)
				{
					ExtendedOrderProcessing eop = new ExtendedOrderProcessing();

					eop.PostSalesOrder(orderId, customerId, ordersDatabase);
				}

				//TODO: probably should receive error messages, if there are any
				//Update labels to reflect the fact that the order has taken place
				Header.Text = "Check Out Complete!";
				Message.Text = "<b>Your Order Number Is: </b>" + orderId;
				SubmitButton.Visible = false;
			}
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.SubmitButton.Click +=
			new System.Web.UI.ImageClickEventHandler(
				this.SubmitButton_Click);
		}

        protected void ShippingDropDownList_SelectedIndexChanged(object sender,
													   System.EventArgs e)
		{
		}

		#endregion
	}

	public class AddressControls
	{
		private TextBox line1;

		private TextBox line2;

		private TextBox city;

		private DropDownList stateProvince;

		private TextBox postalCode;

		public AddressControls(TextBox line1, TextBox line2, TextBox city,
							   DropDownList stateProvince, TextBox postalCode)
		{
			this.line1 = line1;
			this.line2 = line2;
			this.city = city;
			this.stateProvince = stateProvince;
			this.postalCode = postalCode;
		}

		public void FillControls(CustomerAddress ca)
		{
			if (ca.AddressID > -1)
			{
				line1.Text = ca.Line1;
				line2.Text = ca.Line2;
				city.Text = ca.City;
				stateProvince.SelectedValue = ca.StateProvinceID.ToString();
				postalCode.Text = ca.PostalCode;
			}
		}

		public CustomerAddress GetCustomerAddress()
		{
			return new CustomerAddress(0, line1.Text, line2.Text, city.Text,
									   Int32.Parse(stateProvince.SelectedValue,
												   CultureInfo.InvariantCulture),
									   stateProvince.SelectedItem.Text,
									   postalCode.Text);

		}
	}
}