/// <summary>
        /// Christian Lopez
        /// Created: 2017/01/31
        ///
        /// Handles logic of sending data to manager
        /// </summary>
        ///
        /// <remarks>
        /// Aaron Usher
        /// Updated: 2017/04/27
        ///
        /// Changed method call of _supplierManager.CreateSupplier to just send a supplier,
        /// instead of the information piece by piece.
        /// </remarks>
        ///
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <remarks>Last modified 2017/03/09 by Skyler Hiscock</remarks>
        private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            // The process of submitting information to make a supplier in the DB

            // See if we even have a user found for the supplier
            if (!supplierFound && null == _supplierToEdit)
            {
                MessageBox.Show("Please select a supplier.");
            }
            else
            {
                if (_type.Equals("Adding"))
                {
                    try
                    {
                        validateInputs();
                        User     supplierUser = _userManager.RetrieveUserByUserName((string)cboUsername.SelectedItem);
                        Supplier supplier     = new Supplier()
                        {
                            UserId      = supplierUser.UserId,
                            Active      = chkActive.IsChecked.Value,
                            ApprovedBy  = _currentUser.UserId,
                            FarmName    = txtFarmName.Text,
                            FarmAddress = txtFarmAddress.Text,
                            FarmCity    = txtFarmCity.Text,
                            FarmState   = cboFarmState.Text,
                            FarmTaxID   = txtFarmTaxId.Text
                        };
                        // Actually try to create the supplier
                        if (_supplierManager.CreateNewSupplier(supplier))
                        {
                            //this.DialogResult = true;
                            try
                            {
                                addAgreedProducts(supplierUser);
                                this.DialogResult = true;
                            }
                            catch (Exception ex)
                            {
                                if (null != ex.InnerException)
                                {
                                    MessageBox.Show(ex.Message + "\n\n" + ex.InnerException.Message);
                                }
                                else
                                {
                                    MessageBox.Show(ex.Message);
                                }
                            }
                        }
                        else
                        {
                            // If an error was thrown, should go to catch block. This would occur if the number of rows
                            // affected were not one
                            MessageBox.Show("There was an error, where more than one row was affected! Please " +
                                            "contact your Database Admin.");
                        }
                    }
                    catch (Exception ex)
                    {
                        if (null != ex.InnerException)
                        {
                            MessageBox.Show(ex.Message + "\n\n" + ex.InnerException.Message);
                        }
                        else
                        {
                            MessageBox.Show(ex.Message);
                        }
                    }
                }
                else if (_type.Equals("Applying"))
                {
                    try
                    {
                        validateInputs();
                        User supplierUser = _userManager.RetrieveUserByUserName((string)cboUsername.SelectedItem);

                        // Actually try to create the supplier
                        if (_supplierManager.ApplyForSupplierAccount(new Supplier()
                        {
                            UserId = supplierUser.UserId,
                            FarmName = txtFarmName.Text,
                            FarmAddress = txtFarmAddress.Text,
                            FarmCity = txtFarmCity.Text,
                            FarmState = cboFarmState.Text,
                            FarmTaxID = txtFarmTaxId.Text
                        }))

                        //supplierUser.UserId, txtFarmName.Text, txtFarmAddress.Text, txtFarmCity.Text,
                        //cboFarmState.Text, txtFarmTaxId.Text
                        {
                            //this.DialogResult = true;
                            try
                            {
                                addAgreedProducts(supplierUser);
                                this.DialogResult = true;
                            }
                            catch (Exception ex)
                            {
                                if (null != ex.InnerException)
                                {
                                    MessageBox.Show(ex.Message + "\n\n" + ex.InnerException.Message);
                                }
                                else
                                {
                                    MessageBox.Show(ex.Message);
                                }
                            }
                        }
                        else
                        {
                            // If an error was thrown, should go to catch block. This would occur if the number of rows
                            // affected were not one
                            MessageBox.Show("There was an error, where more than one row was affected! Please " +
                                            "contact your Database Admin.");
                        }
                    }
                    catch (Exception ex)
                    {
                        if (null != ex.InnerException)
                        {
                            MessageBox.Show(ex.Message + "\n\n" + ex.InnerException.Message);
                        }
                        else
                        {
                            MessageBox.Show(ex.Message);
                        }
                    }
                }
                else if (_type.Equals("Editing"))
                {
                    // Update suppliers approved products: check if there are agreements that have products
                    // not listed in the approved products list. If so, mark those aggrements as not approved & inactive.
                    // Then see what products in the approved list is not in the agreements, and make agreements for those products.
                    try
                    {
                        Supplier newSupplier = _supplierToEdit.Clone();
                        newSupplier.Active = (bool)chkActive.IsChecked;
                        if (!_supplierManager.UpdateSupplierAccount(_supplierToEdit, newSupplier))
                        {
                            MessageBox.Show("Unable to update supplier information.");
                        }

                        foreach (Agreement a in _agreements)
                        {
                            if (!_agreedProducts.Any(p => p.ProductId == a.ProductId)) // if we cannot find any products in the approved list with matching id
                            {
                                Agreement notApprovedAgreement =
                                    _agreementManager.MakeAgreement(a.AgreementId, a.ProductId, a.SupplierId, DateTime.Now, false, false, _currentUser.UserId);
                                if (!_agreementManager.UpdateAgreement(a, notApprovedAgreement))
                                {
                                    MessageBox.Show("Unable to update agreements");
                                }
                            }
                        }

                        getAgreements();

                        foreach (Product p in _agreedProducts)
                        {
                            if (!_agreements.Any(a => a.ProductId == p.ProductId)) // if we cannot find an agreed product in the list of agreements
                            {
                                _agreementManager.CreateAgreementsForSupplier(_supplierToEdit, p, _currentUser.UserId, true);
                            }
                        }

                        getAgreements();
                        // Update any active agreements that are not approved yet in the agreement list
                        foreach (Agreement a in _agreements)
                        {
                            if (!a.IsApproved)
                            {
                                Agreement update =
                                    _agreementManager.MakeAgreement(a.AgreementId, a.ProductId, a.SupplierId, DateTime.Now, true, a.Active, _currentUser.UserId);
                                if (!_agreementManager.UpdateAgreement(a, update))
                                {
                                    MessageBox.Show("Unable to update agreement for " + _agreedProducts.First(p => p.ProductId == a.ProductId).Name);
                                }
                            }
                        }

                        this.DialogResult = true;
                    }
                    catch (Exception ex)
                    {
                        if (null != ex.InnerException)
                        {
                            MessageBox.Show(ex.Message + "\n\n" + ex.InnerException.Message);
                        }
                        else
                        {
                            MessageBox.Show(ex.Message);
                        }
                    }
                }
            }
        }
        //public ActionResult Create([Bind(Include = "FarmTaxID,UserId,FarmName,FarmAddress,FarmCity,FarmState,Agreements")] SupplierWithAgreements supplierWithAgreements)
        public async Task <ActionResult> Create([Bind(Include =
                                                          "FirstName,LastName,Phone,AddressLineOne,AddressLineTwo,City,State,Zip,EmailAddress,UserName,Password,ConfirmPassword,FarmTaxID,FarmName,FarmAddress,FarmCity,FarmState,ProductIDs")]
                                                SupplierApplicantViewModel supplierApplicant)
        {
            supplierApplicant.Agreements = new List <AgreementWithProductName>();
            if (supplierApplicant.ProductIDs != null)
            {
                for (int i = 0; i < supplierApplicant.ProductIDs.Length; i++)
                {
                    supplierApplicant.Agreements.Add(new AgreementWithProductName()
                    {
                        ProductId   = supplierApplicant.ProductIDs[i],
                        ProductName = _productManager.RetrieveProductById(supplierApplicant.ProductIDs[i]).Name
                    });
                }
            }
            if (ModelState.IsValid)
            {
                //Need to first make a user with the information, then the supplier
                User newUser = new User()
                {
                    FirstName        = supplierApplicant.FirstName,
                    LastName         = supplierApplicant.LastName,
                    City             = supplierApplicant.City,
                    State            = supplierApplicant.State,
                    AddressLineOne   = supplierApplicant.AddressLineOne,
                    AddressLineTwo   = supplierApplicant.AddressLineTwo,
                    Zip              = supplierApplicant.Zip,
                    EmailAddress     = supplierApplicant.EmailAddress,
                    EmailPreferences = true,
                    Active           = true,
                    Phone            = supplierApplicant.Phone,
                    UserName         = supplierApplicant.UserName
                };

                try
                {
                    string result = _userManager.CreateNewUser(newUser, supplierApplicant.Password, supplierApplicant.ConfirmPassword);
                    if (!("Created".Equals(result)))
                    {
                        ViewBag.Message = result;
                        return(View(supplierApplicant));
                    }
                }
                catch (Exception)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.ServiceUnavailable));
                }

                // If we are here, it means we created the user
                User newlyCreated = null;
                try
                {
                    newlyCreated = _userManager.RetrieveUserByUserName(newUser.UserName);
                }
                catch (Exception)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.ServiceUnavailable));
                }

                if (null == newlyCreated) // this shouldn't ever be true
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError));
                }

                // Make a supplier and store the associated data to the db
                SupplierWithAgreements supplierWithAgreements = new SupplierWithAgreements()
                {
                    FarmName    = supplierApplicant.FarmName,
                    FarmAddress = supplierApplicant.FarmAddress,
                    FarmCity    = supplierApplicant.FarmCity,
                    FarmState   = supplierApplicant.FarmState,
                    FarmTaxID   = supplierApplicant.FarmTaxID,
                    UserId      = newlyCreated.UserId,
                    ProductIDs  = supplierApplicant.ProductIDs,
                    Agreements  = supplierApplicant.Agreements,
                    Active      = true,
                    IsApproved  = false
                };
                try
                {
                    if (_supplierManager.ApplyForSupplierAccount(supplierWithAgreements))
                    {
                        supplierWithAgreements.SupplierID = _supplierManager.RetrieveSupplierByUserId(supplierWithAgreements.UserId).SupplierID;
                        foreach (Agreement a in supplierWithAgreements.Agreements)
                        {
                            if (!_agreementManager.CreateAgreementsForSupplier(supplierWithAgreements, _productManager.RetrieveProductById(a.ProductId)))
                            {
                                return(new HttpStatusCodeResult(HttpStatusCode.ServiceUnavailable));
                            }
                        }

                        RegisterViewModel registerModel = new RegisterViewModel()
                        {
                            Email           = newUser.EmailAddress,
                            Password        = supplierApplicant.Password,
                            ConfirmPassword = supplierApplicant.ConfirmPassword
                        };


                        var controller = DependencyResolver.Current.GetService <AccountController>();
                        controller.ControllerContext = new ControllerContext(this.Request.RequestContext, controller);

                        var result = await controller.Register(registerModel);

                        return(RedirectToAction("ApplicationSuccess", "Home", new { username = newlyCreated.UserName, supOrCom = true }));
                        //return RedirectToAction("Register", "Account", registerModel);
                    }
                    else
                    {
                        return(new HttpStatusCodeResult(HttpStatusCode.ServiceUnavailable));
                    }
                }
                catch (Exception)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.ServiceUnavailable));
                }
            }

            List <Product> products = _productManager.ListProducts();

            supplierApplicant.Agreements = new List <AgreementWithProductName>();
            foreach (Product p in products)
            {
                supplierApplicant.Agreements.Add(new AgreementWithProductName()
                {
                    ProductId   = p.ProductId,
                    ProductName = p.Name
                });
            }

            return(View(supplierApplicant));
        }