public ActionResult DeleteList(FormCollection collection)
        {
            try
            {
                int listId = int.Parse(collection["ShoppingList_Id"].ToString());

                ShoppingListService listService     = new ShoppingListService();
                LanguageService     languageService = new LanguageService();
                var langId = languageService.GetByCode(Session["LanguageCode"].ToString()).Id;

                //TO DO: delete all related entries (ShoppingListEntry)
                ProductService productService = new ProductService();
                var            listEntries    = productService.GetEntriesAsProducts(listId, langId);

                foreach (ProductDto product in listEntries)
                {
                    DeleteItem(product.Id, listId);
                }

                //delete ListSorting
                UserListSortingService listSortingService = new UserListSortingService();
                listSortingService.Delete((int)listService.Get(listId).ChosenSortingId);

                //delete list itself & all links in LinkUserToList
                listService.Delete(listId);

                TempData["SuccessMessage"] = "The list was successfully deleted.";
                return(RedirectToAction("Lists"));
            }
            catch
            {
                TempData["ErrorMessage"] = "Deleting the list wasn't successful. Try again.";
                return(RedirectToAction("Lists"));
            }
        }
        public ActionResult RenameList(FormCollection collection)
        {
            try
            {
                var newName = collection["ListName"];
                int listId  = int.Parse(collection["ShoppingList_Id"]);

                ShoppingListService listService = new ShoppingListService();
                var dbList = listService.Get(listId);

                if (newName == dbList.Name)
                {
                    throw new Exception("The name of the list is unchanged.");
                }

                ShoppingListDto list = new ShoppingListDto
                {
                    Id   = listId,
                    Name = newName
                };

                listService.Update(list);

                TempData["SuccessMessage"] = "The list's name was successfully updated!";
                return(Redirect(Request.UrlReferrer.ToString()));
            }
            catch
            {
                TempData["ErrorMessage"] = "Updating the list's name wasn't successful.";
                return(Redirect(Request.UrlReferrer.ToString()));
            }
        }
        public void TestGetIncludeListItems()
        {
            var mockShoppingListRepository = new Mock <IShoppingListRepository>(MockBehavior.Strict);

            mockShoppingListRepository.Setup(slr => slr.Get(shoppingListGetId, true, false)).Returns(
                new ShoppingList
            {
                Id        = shoppingListGetId, Title = "Test list to get", CreatorId = userIds[0], CreatedDate = DateTime.Now,
                ListItems = new List <ListItem>()
                {
                    new ListItem {
                        Description = "Test list item 1", ShoppingListId = shoppingListGetId, CreatorId = userIds[0], CreatedDate = DateTime.Now
                    },
                    new ListItem {
                        Description = "Test list item 2", ShoppingListId = shoppingListGetId, CreatorId = userIds[0], CreatedDate = DateTime.Now
                    }
                }
            }
                );
            container.StartMocking <IShoppingListRepository>(() => mockShoppingListRepository.Object);
            CreateMockPermission(Permissions.View, shoppingListGetId, userIds[0]);
            service = container.GetInstance <ShoppingListService>();

            var shoppingList = service.Get(shoppingListGetId, userIds[0], includeListItems: true);

            Assert.AreEqual(2, shoppingList.ListItems.Count());
        }
        public void TestGetEntityNotFound()
        {
            var mockShoppingListRepository = new Mock <IShoppingListRepository>(MockBehavior.Strict);

            mockShoppingListRepository.Setup(slr => slr.Get(shoppingListNotExistingId, false, false)).Returns <ShoppingList>(null);
            container.StartMocking <IShoppingListRepository>(() => mockShoppingListRepository.Object);
            CreateMockPermission(Permissions.View, shoppingListNotExistingId, userIds[0]);
            service = container.GetInstance <ShoppingListService>();

            var shoppingList = service.Get(shoppingListNotExistingId, userIds[0]); // Should throw EntityNotFoundException.
        }
        // GET: List/Item/Delete/5
        public ActionResult DeleteItem(int id, int listId)  //id = productId
        {
            //try
            //{
            //1. If UserProduct -> Delete
            ProductService productService = new ProductService();
            var            prodType       = productService.GetProductTypeId(id);

            if (prodType == 4)     //one-time UserProduct
            {
                var userProdId = productService.GetUserProductId(id);
                productService.DeleteUserProduct(userProdId);
            }

            //2. Update Sorting without this item
            LanguageService        languageService    = new LanguageService();
            var                    listEntries        = productService.GetEntriesAsProducts(listId, languageService.GetByCode(Session["LanguageCode"].ToString()).Id);
            UserListSortingService listSortingService = new UserListSortingService();
            ShoppingListService    listService        = new ShoppingListService();
            var                    sortingId          = listService.Get(listId, int.Parse(Session["UserId"].ToString())).ChosenSortingId;
            UserListSortingDto     sorting            = new UserListSortingDto();

            if (sortingId != null)
            {
                sorting.Id = (int)sortingId;
            }
            sorting.ShoppingList_Id = listId;

            ShoppingListEntryService shoppingListEntryService = new ShoppingListEntryService();
            var entryId = shoppingListEntryService.GetEntryId(id, listId);

            listSortingService.SaveSorting(sorting, listEntries, entryId);

            //3. Delete ShoppingListEntry (if default or reusable only this)
            shoppingListEntryService.Delete(entryId);

            TempData["SuccessMessage"] = "Successfully deleted the entry.";
            return(RedirectToAction("SingleList", new { @id = listId }));
            //}
            //catch
            //{
            //    TempData["ErrorMessage"] = "There was an error while trying to delete this entry.";
            //    return Redirect(Request.UrlReferrer.ToString());
            //}
        }
        public void TestGetWithoutIncludes()
        {
            var mockShoppingListRepository = new Mock <IShoppingListRepository>(MockBehavior.Strict);

            mockShoppingListRepository.Setup(slr => slr.Get(shoppingListGetId, false, false)).Returns(
                new ShoppingList
            {
                Id = shoppingListGetId, Title = "Test list to get", CreatorId = userIds[0], CreatedDate = DateTime.Now
            }
                );
            container.StartMocking <IShoppingListRepository>(() => mockShoppingListRepository.Object);
            CreateMockPermission(Permissions.View, shoppingListGetId, userIds[0]);
            service = container.GetInstance <ShoppingListService>();

            var shoppingList = service.Get(shoppingListGetId, userIds[0]);

            Assert.IsNull(shoppingList.ListItems);
        }
        public ActionResult CreateItem(FormCollection collection)
        {
            try
            {
                var name            = collection["Name"];
                var reusable        = collection["UserProduct"];
                var price           = decimal.Parse(collection["Price"]);
                var listId          = int.Parse(collection["ShoppingList_Id"]);
                var qty             = int.Parse(collection["quantity"]);
                var unitTypeId      = int.Parse(collection["UnitTypesListId"]); //TODO: create lists in view and get id (like for countries/languages)
                var catId           = int.Parse(collection["CategoryListId"]);
                var userCat         = collection["UserCategory"];
                int userCatId       = 0;
                var currencyId      = int.Parse(collection["CurrencyListId"]);
                int prodType        = 0;
                var prodId          = 0;
                var chosenProductId = collection["ChosenProductId"]; //gets defaultProductId from dropdown

                if (name != "" && chosenProductId != "")             //Name filled in and defaultProduct chosen
                {
                    throw new Exception("You can either create a new item or choose from the default products, but not both!");
                }

                LanguageService languageService = new LanguageService();
                if (userCat != "")
                {
                    CategoryDto category = new CategoryDto
                    {
                        Name       = userCat,
                        LanguageId = languageService.GetByCode(Session["LanguageCode"].ToString()).Id,
                        UserId     = int.Parse(Session["UserId"].ToString())
                    };

                    CategoryService categoryService = new CategoryService();
                    userCatId = categoryService.Create(category);
                }

                ShoppingListEntryService entryService   = new ShoppingListEntryService();
                ProductService           productService = new ProductService();

                if (name != "") //IF UserProduct -> create Product - ShoppingListEntry - UserProduct
                {
                    if (reusable == "false")
                    {
                        prodType = 4;   //4 = UserListProduct = non reusable
                    }
                    else
                    {
                        prodType = 3;   //reusable UserProduct
                    }

                    //create a new Product
                    ProductDto productDto = new ProductDto
                    {
                        ProductTypeId = prodType
                    };
                    prodId = productService.Create(productDto);

                    //create new UserProduct
                    UserProductDto userProduct = new UserProductDto
                    {
                        ProductId = prodId,
                        Name      = name
                    };
                    if (userCat != "")
                    {
                        userProduct.Category_Id = userCatId;
                    }
                    else
                    {
                        userProduct.Category_Id = catId;
                    }
                    userProduct.User_Id     = int.Parse(Session["UserId"].ToString());
                    userProduct.Unit_Id     = unitTypeId;
                    userProduct.Price       = price;
                    userProduct.Currency_Id = currencyId;

                    entryService.Create(userProduct);
                }
                else if (chosenProductId != "")   //IF DefaultProduct -> create ShoppingListEntry & LinkDefaultProductToUser
                {
                    //check if chosen defaultProduct or reusable UserProduct
                    prodId   = int.Parse(chosenProductId);
                    prodType = productService.GetProductTypeId(prodId);

                    if (prodType == 1)    //if DefaultProduct: create Link entry
                    {
                        DefaultProductDto defaultProductDto = new DefaultProductDto
                        {
                            Id = productService.GetDefaultProductId(prodId)
                        };
                        productService.CreateLink(defaultProductDto, int.Parse(Session["UserId"].ToString()));
                    }

                    //if reusable UserProduct: only create ShoppingListEntry
                }

                //create Entry if not existent right now!
                var existentEntries = entryService.GetEntriesByListId(listId);
                foreach (ShoppingListEntryDto shoppingListEntry in existentEntries)
                {
                    if (shoppingListEntry.Product_Id == prodId)
                    {
                        throw new Exception("You can't add the same product to your list twice.");
                    }
                }

                ShoppingListEntryDto entry = new ShoppingListEntryDto
                {
                    Quantity        = qty,
                    Product_Id      = prodId,
                    ShoppingList_Id = listId,
                    State_Id        = 2 //Default is unchecked
                };
                entryService.Create(entry);

                //Update ShoppingList to update Timestamp:
                ShoppingListDto shoppingList = new ShoppingListDto
                {
                    Id = listId
                };
                ShoppingListService listService = new ShoppingListService();
                listService.Update(shoppingList);

                // Update Sorting
                var listEntries = productService.GetEntriesAsProducts(listId, languageService.GetByCode(Session["LanguageCode"].ToString()).Id);
                UserListSortingService listSortingService = new UserListSortingService();
                var sortingId = listService.Get(listId, int.Parse(Session["UserId"].ToString())).ChosenSortingId;
                UserListSortingDto sorting = new UserListSortingDto();
                if (sortingId != null)
                {
                    sorting.Id = (int)sortingId;
                }
                sorting.ShoppingList_Id = listId;
                listSortingService.SaveSorting(sorting, listEntries);

                TempData["SuccessMessage"] = "Successfully created a new item";
                return(RedirectToAction("SingleList", new { @id = listId }));
            }
            catch
            {
                TempData["ErrorMessage"] = "There was an error while creating a new item. Be aware that you can only create a new item or choose from the dropdown list of default products and your own reusable items, but you can't do both.";
                return(Redirect(Request.UrlReferrer.ToString()));
            }
        }
        // GET: User/SingleList
        public ActionResult SingleList(int?id, int?templateId, int?sortingId)
        {
            if (Session["UserId"] != null && id != null)
            {
                ViewBag.Message = TempData["SuccessMessage"];
                ViewBag.Error   = TempData["ErrorMessage"];

                ShoppingListService listService = new ShoppingListService();
                var userLists     = listService.GetListsByUserId(int.Parse(Session["UserId"].ToString()));
                var requestedList = listService.Get((int)id);

                //checking whether the list the user tries to access is his or if he has access rights
                foreach (ShoppingListDto x in userLists)
                {
                    if (x.Id == requestedList.Id)
                    {
                        SingleListVM list = new SingleListVM
                        {
                            ShoppingList_Id = requestedList.Id
                        };

                        var listObj = listService.Get(list.ShoppingList_Id, int.Parse(Session["UserId"].ToString()));

                        list.ListName         = listObj.Name;
                        list.ListAccessTypeId = listObj.ListAccessTypeId;

                        LanguageService languageService = new LanguageService();
                        var             langId          = languageService.GetByCode(Session["LanguageCode"].ToString()).Id;

                        ProductService productService = new ProductService();
                        list.ListEntries = productService.GetEntriesAsProducts(list.ShoppingList_Id, langId);

                        if (list.ListEntries.Count() == 0)
                        {
                            ViewBag.Message = "You don't have any entries yet. Start creating your entries now!";
                        }

                        TemplateSortingService templateService    = new TemplateSortingService();
                        UserListSortingService listSortingService = new UserListSortingService();
                        UserListSortingDto     sorting            = new UserListSortingDto();
                        if (listObj.ChosenSortingId != null)
                        {
                            sorting.Id = (int)listObj.ChosenSortingId;
                        }
                        sorting.ShoppingList_Id = list.ShoppingList_Id;

                        if (listObj.ChosenSortingId != null)
                        {
                            list.ListEntries = listSortingService.ApplyUserSorting((int)listObj.ChosenSortingId, list.ListEntries);
                        }

                        if (templateId != null)
                        {
                            list.ListEntries = templateService.SortByTemplate((int)templateId, list.ListEntries);
                            listSortingService.SaveSorting(sorting, list.ListEntries);
                            ViewBag.Message = "Your list has been sorted according to the template. This sorting has been saved permanently for you.";
                        }
                        else if (sortingId != null)
                        {
                            switch ((int)sortingId)
                            {
                            case 1:     // A - Z
                            {
                                list.ListEntries = list.ListEntries.OrderBy(z => z.Name).ToList();
                                listSortingService.SaveSorting(sorting, list.ListEntries);
                                break;
                            }

                            case 2:     // Z - A
                            {
                                list.ListEntries = list.ListEntries.OrderByDescending(z => z.Name).ToList();
                                listSortingService.SaveSorting(sorting, list.ListEntries);
                                break;
                            }

                            case 3:     // lowest price
                            {
                                list.ListEntries = list.ListEntries.OrderBy(z => z.Price).ToList();
                                listSortingService.SaveSorting(sorting, list.ListEntries);
                                break;
                            }

                            case 4:     // highest price
                            {
                                list.ListEntries = list.ListEntries.OrderByDescending(z => z.Price).ToList();
                                listSortingService.SaveSorting(sorting, list.ListEntries);
                                break;
                            }

                            default: break;
                            }
                        }

                        list.ChosenProductId    = 0; //By default no defaultProduct should be selected
                        list.ChooseProductsList = (from item in productService.GetDefaultAndReusableProductsByLanguage(langId)
                                                   select new SelectListItem()
                        {
                            Text = item.Name,
                            Value = item.ProductId.ToString()
                        }).ToList();

                        UnitTypeService unitTypeService = new UnitTypeService();
                        list.UnitTypesListId = 8; //default value: pc.
                        list.UnitTypesList   = (from item in unitTypeService.GetUnitTypesByLanguage(langId)
                                                select new SelectListItem()
                        {
                            Text = item.Name,
                            Value = item.Id.ToString()
                        }).ToList();

                        CurrencyService currencyService = new CurrencyService();
                        list.CurrencyListId = 5; //default DKK
                        list.CurrencyList   = (from item in currencyService.GetAll()
                                               select new SelectListItem()
                        {
                            Text = item.Code,
                            Value = item.Id.ToString()
                        }).ToList();

                        CategoryService categoryService = new CategoryService();
                        list.CategoryListId = 20; //default category: others
                        list.CategoryList   = (from item in categoryService.GetAllCategories(langId, int.Parse(Session["UserId"].ToString()))
                                               select new SelectListItem()
                        {
                            Text = item.Name,
                            Value = item.Id.ToString()
                        }).ToList();

                        list.ChosenTemplateId = 0;
                        list.Templates        = (from item in templateService.GetTemplates()
                                                 select new SelectListItem()
                        {
                            Text = item.TemplateName,
                            Value = item.Id.ToString()
                        }).ToList();

                        return(View(list));
                    }
                }

                TempData["ErrorMessage"] = "The list you tried to access isn't yours!!";
                return(RedirectToAction("Lists", "List"));
            }
            else
            {
                return(RedirectToAction("Login", "User"));
            }
        }