public object Convert(object value, Type type, object parameter, string language)
        {
            string result = "";

            if (value != null)
            {
                StringBuilder gridText = new StringBuilder();
                Dictionary<float, float> mealItemIDs = (Dictionary<float, float>)value;
                MealItemViewModel mealItem = new MealItemViewModel();
                int loopCount = 0;

                foreach (var mealItemID in mealItemIDs)
                {
                    mealItem = mealItem.GetMealItemById((int)mealItemID.Key);

                    if (mealItem != null)
                    {
                        if (loopCount < mealItemIDs.Count - 1)
                            gridText.Append(mealItem.Name).Append(", ");
                        else
                            gridText.Append(mealItem.Name);
                    }

                    loopCount++;
                }

                result = gridText.ToString();
            }

            return result;
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            Type type = e.Parameter.GetType();
            TotalAmountUOMTextBox.ItemsSource = _unitOfMeasureList;

            if (type == typeof(FoodCategoryViewModel))
            {
                FoodCategoryViewModel category = (FoodCategoryViewModel)e.Parameter;
                CategoryTextBox.Text = category.Name;
                CategoryTextBox.IsReadOnly = true;
                _existingMealItem = new MealItemViewModel();
                _existingMealItem.Category = category.Name;
            }
            else if (type == typeof(MealItemViewModel))
            {
                _existingMealItem = (MealItemViewModel)e.Parameter;
                CategoryTextBox.Text = _existingMealItem.Category;
                CategoryTextBox.IsReadOnly = true;
                NameTextBox.Text = _existingMealItem.Name;
                NameTextBox.IsReadOnly = true;
                ingredientsViewModel = new IngredientsViewModel();
                _selectedIngredientsList = ingredientsViewModel.GetIngredients(_existingMealItem.IngredientIDsWithTotalAmount);
                TotalAmountTextBox.Text = _existingMealItem.TotalAmount.ToString();
                TotalAmountUOMTextBox.SelectedIndex = _existingMealItem.TotalAmountUnitOfMeasure-1;

                var copy = new ObservableCollection<IngredientViewModel>(_selectedIngredientsList);
                foreach (var ingredient in copy)
                {
                    FindAndRemoveIngredient(_allIngredients, ingredient);
                }
            }

            AllIngredientsList.ItemsSource = _allIngredients;
            SelectedIngredientsList.ItemsSource = _selectedIngredientsList;           
        }
        private async void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            if (_existingMealItem == null)
            {
                _existingMealItem = new MealItemViewModel();
                _existingMealItem.Name = NameTextBox.Text.ToString();
                _existingMealItem.Category = CategoryTextBox.Text.ToString();
            }

            if (NameTextBox.Text == "")
            {
                var dialog = new MessageDialog("Bitte einen Namen angeben.");
                await dialog.ShowAsync();
                return;
            }

            if (_existingMealItem.Name == "")
                _existingMealItem.Name = NameTextBox.Text.ToString();

            _existingMealItem.TotalAmount = float.Parse(TotalAmountTextBox.Text, CultureInfo.InvariantCulture.NumberFormat);
            UnitOfMeasureViewModel unitOfMeasure = (UnitOfMeasureViewModel)TotalAmountUOMTextBox.SelectedItem;
            _existingMealItem.TotalAmountUnitOfMeasure = unitOfMeasure.Id;

            string result = _existingMealItem.SaveMealItem(_existingMealItem);
            
        }
        private void MealItemsGridView_ItemClick(object sender, ItemClickEventArgs e)
        {
            currentSelectedMealItem = (MealItemViewModel)e.ClickedItem;
            WeightTextBlock.Visibility = Visibility.Visible;
            WeightTextBox.Visibility = Visibility.Visible;

            UnitOfMeasureViewModel unitOfMeasure = new UnitOfMeasureViewModel();
            string unitOfMeasureName = unitOfMeasure.GetUnitOfMeasure(currentSelectedMealItem.TotalAmountUnitOfMeasure).UnitName;
            WeightTextBlock.Text = "Menge in " + unitOfMeasureName;

            string mealItemWeight = "";
            if (_meal.MealItemIDsWithWeight[currentSelectedMealItem.Id] > 0)
            {
                mealItemWeight = this._meal.MealItemIDsWithWeight[currentSelectedMealItem.Id].ToString();
            }
            else
            {
                float mealItemWeightDefault = currentSelectedMealItem.TotalAmount;
                int numberGuestes = Int32.Parse(NumberOfGuestsTextBox.Text);
                float totalWeight = mealItemWeightDefault * numberGuestes;
                mealItemWeight = totalWeight.ToString();
            }

            WeightTextBox.Text = mealItemWeight.Replace('.', ',');
        }
        private void ResetWeightsInvokedHandler(IUICommand command)
        {
            if (command.Label == "Ja")
            {
                float mealItemTotalWeight = 0;

                if (NumberOfGuestsTextBox.Text != "")
                {
                    int numberOfGuests = Int32.Parse(NumberOfGuestsTextBox.Text);
                    MealItemViewModel defaultMealItem = new MealItemViewModel();

                    foreach (var mealIDAndWeight in _meal.MealItemIDsWithWeight.ToList())
                    {
                        defaultMealItem = defaultMealItem.GetMealItemById((int)mealIDAndWeight.Key);
                        mealItemTotalWeight = defaultMealItem.TotalAmount;

                        decimal roundedWeight = Math.Round((decimal)(mealItemTotalWeight * numberOfGuests), 0);
                        _meal.MealItemIDsWithWeight[mealIDAndWeight.Key] = (float)roundedWeight;
                    }
                }
            }
        }
        private async void ImportMealItemsData(string fileContent, string mealItemCategory)
        {
            string line = "";
            string[] mealItemsRaw = fileContent.Split('|');
            char[] trimChar = {'\n','\r'};
            bool mealItemExists = false;

            foreach(var mealItemRaw in mealItemsRaw)
            {
                if (mealItemRaw.ToString().Length == 0) { continue; }
                string mealItemInfo = mealItemRaw.TrimStart(trimChar);
                using (System.IO.StringReader stringReader = new System.IO.StringReader(mealItemInfo))
                {
                    int lineNo = 0;
                    string mealItemName = "";
                    float grossWeight = 0;
                    float divisionFactor = 0;
                    string grossWeightUnitOfMeasure = "";
                    List<string> rawIngredients = new List<string>();

                    while ((line = await stringReader.ReadLineAsync()) != null)
                    {
                        // At 0 this should be the name
                        if (lineNo == 0)
                        {
                            mealItemName = CleanMealItemName(line);
                            MealItemViewModel mealItemView = new MealItemViewModel();
                            // In case the meal item exists we move on to the next
                            if (mealItemView.MealItemExists(mealItemName) == true) { mealItemExists = true; break; }
                            lineNo++;
                            continue;
                        }

                        if (line.Contains("Personen"))
                        {
                            string _grossWeight;
                            string _divisionFactor;
                            GetGrossWeightAndDivisionFactor(line, out _grossWeight, 
                                out grossWeightUnitOfMeasure, out _divisionFactor);
                            _divisionFactor = _divisionFactor.Replace(',', '.');
                            _grossWeight = _grossWeight.Replace(',', '.');
                            divisionFactor = float.Parse(_divisionFactor, CultureInfo.InvariantCulture.NumberFormat);
                            grossWeight = float.Parse(_grossWeight, CultureInfo.InvariantCulture.NumberFormat) / divisionFactor;
                            
                            lineNo++;
                            continue;
                        }

                        rawIngredients = InterpretIngredientDefinition(line);
                        lineNo++;
                    }

                    // Let's see if there was an inner break
                    if (mealItemExists) { mealItemExists = false; continue; }

                    // if go this far it means a new meal item
                    MealItemViewModel mealItem = new MealItemViewModel();
                    IngredientViewModel ingredient = null;
                    foreach (var rawIngredient in rawIngredients)
                    {
                        string amount;
                        string unitOfMeasure;
                        ingredient = GetIngredientDetails(rawIngredient, out amount, out unitOfMeasure);

                        if (ingredient != null)
                        {
                            UnitOfMeasureViewModel unitOfMeasureModel = new UnitOfMeasureViewModel();
                            unitOfMeasureModel = unitOfMeasureModel.GetUnitOfMeasure(ingredient.UnitOfMeasure);
                            amount = amount.Replace(',', '.');
                            float floatAmount = float.Parse(amount, CultureInfo.InvariantCulture.NumberFormat);

                            // Recalculating kilogramms and liters
                            if ((unitOfMeasure.Equals("kg", StringComparison.CurrentCultureIgnoreCase)) ||
                                    (unitOfMeasure.Equals("Ltr", StringComparison.CurrentCultureIgnoreCase)))
                                floatAmount = floatAmount * 1000;
                            // Devive by the number of people all amounts were calculated for
                            floatAmount = floatAmount / divisionFactor;
                            mealItem.IngredientIDsWithTotalAmount.Add(ingredient.Id, floatAmount);
                        }
                    }

                    mealItem.Name = mealItemName;
                    if (grossWeightUnitOfMeasure.Equals("Ltr", StringComparison.CurrentCultureIgnoreCase) ||
                        grossWeightUnitOfMeasure.Equals("kg", StringComparison.CurrentCultureIgnoreCase))
                        grossWeight = grossWeight * 1000;

                    if (grossWeightUnitOfMeasure.Equals("kg", StringComparison.CurrentCultureIgnoreCase) ||
                        grossWeightUnitOfMeasure.Equals("g", StringComparison.CurrentCultureIgnoreCase))
                        mealItem.TotalAmountUnitOfMeasure = 1;

                    if (grossWeightUnitOfMeasure.Equals("Ltr", StringComparison.CurrentCultureIgnoreCase) ||
                        grossWeightUnitOfMeasure.Equals("ml", StringComparison.CurrentCultureIgnoreCase))
                        mealItem.TotalAmountUnitOfMeasure = 2;

                    mealItem.TotalAmount = grossWeight;
                    FoodCategoryViewModel mealItemCategoryModel = new FoodCategoryViewModel();
                    mealItemCategoryModel = mealItemCategoryModel.GetFoodCategoryByName(mealItemCategory);
                    if (mealItemCategoryModel != null) { mealItem.CategoryId = mealItemCategoryModel.Id; }
                    _mealItems.Add(mealItem);
                     
                }
            }
        }
        public string SaveMealItem(MealItemViewModel mealitem)
        {
            string result = string.Empty;
            using (var db = new SQLite.SQLiteConnection(App.DBPath))
            {
                string change = string.Empty;
                try
                {
                    var existingMealItem = (db.Table<MealItem>().Where(
                        c => c.Id == mealitem.Id)).SingleOrDefault();

                    if (existingMealItem != null)
                    {
                        existingMealItem.Name = mealitem.Name;
                        existingMealItem.Category = mealitem.Category;
                        existingMealItem.TotalAmount = mealitem.TotalAmount;
                        existingMealItem.TotalAmountUnitOfMeasure = mealitem.TotalAmountUnitOfMeasure;
                        existingMealItem.CategoryId = ((db.Table<FoodCategory>().Where(c => c.Name == mealitem.Category)).Single()).Id;
                        existingMealItem.IngredientIDsWithTotalAmount = (byte[])_dictionaryConverterFloat.Convert(mealitem.IngredientIDsWithTotalAmount, null, null, "");

                        int success = db.Update(existingMealItem);
                    }
                    else
                    {
                        var foodCategory = (db.Table<FoodCategory>().Where(c => c.Name == mealitem.Category)).Single();

                        int success = db.Insert(new MealItem()
                        {
                            Name = mealitem.Name,
                            Category = mealitem.Category,
                            CategoryId = foodCategory.Id,
                            TotalAmount = mealitem.TotalAmount,
                            TotalAmountUnitOfMeasure = mealitem.TotalAmountUnitOfMeasure,
                            IngredientIDsWithTotalAmount = (byte[])_dictionaryConverterFloat.Convert(mealitem.IngredientIDsWithTotalAmount, null, null, "")
                        });
                    }

                    result = "Success";
                }
                catch
                {
                    result = "This meal item was not saved.";
                }
            }

            return result;
        }
        public MealItemViewModel GetMealItemById(int meaItemId)
        {
            var mealitem = new MealItemViewModel();
            using (var db = new SQLite.SQLiteConnection(App.DBPath))
            {
                try
                {
                    var _mealitem = (db.Table<MealItem>().Where(
                        c => c.Id == meaItemId)).Single();
                    mealitem.Id = _mealitem.Id;
                    mealitem.Name = _mealitem.Name;
                    mealitem.Category = _mealitem.Category;
                    mealitem.TotalAmount = _mealitem.TotalAmount;
                    mealitem.TotalAmountUnitOfMeasure = _mealitem.TotalAmountUnitOfMeasure;
                    mealitem.IngredientIDsWithTotalAmount = (Dictionary<float, float>)_dictionaryConverterFloat.ConvertBack(_mealitem.IngredientIDsWithTotalAmount, null, null, "");
                }
                catch
                { }
            }

            return mealitem;
        }
        private string GetIngredientsAsText(IngredientsViewModel ingredientsView, 
            MealItemViewModel mealItem, Dictionary<float,float> mealItemIDsWithWeight)
        {
            StringBuilder sb = new StringBuilder();
            ObservableCollection<IngredientViewModel> ingredients =
                    ingredientsView.GetIngredients(mealItem.IngredientIDsWithTotalAmount);

            if (ingredients.Count > 0)
            {
                //sb.Append(@"\b ");
                int loopCount = 0;
                UnitOfMeasureViewModel unitOfMeasure = new UnitOfMeasureViewModel();
                MealItemViewModel defaultMealItem = new MealItemViewModel();
                defaultMealItem = defaultMealItem.GetMealItemById(mealItem.Id);

                foreach (var ingredient in ingredients)
                {
                    float ingredientDefaultWeight = mealItem.IngredientIDsWithTotalAmount[ingredient.Id];
                    if (defaultMealItem.TotalAmount == 0) defaultMealItem.TotalAmount = 1;
                    float ingredientWeight = (ingredientDefaultWeight / defaultMealItem.TotalAmount) * mealItemIDsWithWeight[mealItem.Id];
                    decimal roundedIngredientWeight = Math.Round((decimal)ingredientWeight, 0);
                    string uomName = unitOfMeasure.GetUnitOfMeasure(ingredient.UnitOfMeasure).Abbreviation;
                    sb.Append(roundedIngredientWeight.ToString());
                    sb.Append(uomName).Append(" ");
                    sb.Append(ingredient.Name);

                    if ((ingredients.Count >1) && (loopCount < (ingredients.Count-1)))
                    { sb.Append(", "); }

                    loopCount++;
                }

                //sb.Append(@"\line\b0");
                sb.Append(@"\line");
                return sb.ToString();
            }
            else
                return "";
        }
        public string SetDefaultMealItemWeights(IMealViewModel meal)
        {
            string result = "";
            MealItemViewModel mealItem = new MealItemViewModel();

            foreach (var mealItemKeyValue in meal.MealItemIDsWithWeight.ToList())
            {
                mealItem = mealItem.GetMealItemById((int)mealItemKeyValue.Key);
                float mealItemWeightDefault = mealItem.TotalAmount;
                float totalWeight = mealItemWeightDefault * meal.NumberOfGuests;
                meal.MealItemIDsWithWeight[mealItemKeyValue.Key] = totalWeight;
            }

            return result;
        }