public void HandleHistoryItemClicked(Order order)
 {
     if (order != null)
     {
         if (ExistingOrder != null)
             order.OrderId = ExistingOrder.OrderId;
         else
             order.OrderId = null;
         Navigator.PushAsync<OrderFormViewModel>((vm) => vm.SetOrder(order));
     }
 }
        public void SetOrder(Order order)
        {
            Order = order;

            ResetFields();
        }
        public async Task UpsertOrder(Order order)
        {
            if (string.IsNullOrEmpty(order.OrderItem) && string.IsNullOrEmpty(order.Soup) && string.IsNullOrEmpty(order.OrderComments))
            {
                throw new Exception("You must fill at least one field.");
            }
                
            await FetchOrderingStatus();

            if (!OrderingStatusOpen)
            {
                throw new Exception("Lunch ordering is closed :(.\nPlease contact the responsible team directly.");
            }

            order.AddDate = DateTime.UtcNow;
            order.UserId = LoginManager.LoggedinUser.UserId;

            using (var client = new HttpClient(new NativeMessageHandler()))
            {
                var method = order.OrderId.HasValue ? HttpMethod.Put : HttpMethod.Post;
                using (var req = new HttpRequestMessage(method, Configuration.Routes.Order))
                {
                    try
                    {
                        var history = await GetHistory();
                        var json = JsonConvert.SerializeObject(order);
                        req.Content = new JsonContent(json);

                        if (order.OrderId.HasValue)
                        {
                            await client.RequestAsync(req);
                            history[order.RestaurantId].RemoveAll(o => o.OrderId == order.OrderId);
                        }
                        else
                        {
                            var res = await client.RequestAsync<int>(req);
                            order.OrderId = res.Data;
                        }

                        history[order.RestaurantId].Add(order);
                        var sorted = history[order.RestaurantId].OrderByDescending(o => o.AddDate).ToList();
                        history[order.RestaurantId] = sorted;
                        await BlobCache.InMemory.InsertObject<Dictionary<int, List<Order>>>(Configuration.CacheKeys.OrderHistory, history);
                    }
                    catch (NetworkException e)
                    {
                        throw new Exception("You must be online.", e);
                    }
                    catch (Exception e)
                    {
                        throw new Exception("Unable to create order. Error:" + e.FullMessage(), e);
                    }
                }
            }
        }
        public async Task DeleteOrder(Order order)
        {
            await FetchOrderingStatus();

            if (!OrderingStatusOpen)
            {
                throw new Exception("Lunch ordering is closed :(.\nPlease contact the responsible team directly.");
            }
//            #if DEBUG
//            throw new Exception("Not Available in Debug Mode");
//            #endif

            using (var client = new HttpClient(new NativeMessageHandler()))
            {
                using (var req = new HttpRequestMessage(HttpMethod.Delete, Configuration.Routes.Order + "/?orderid=" + order.OrderId))
                {
                    try
                    {
                        await client.RequestAsync(req);
                      
                        var history = await GetHistory();
                        history[order.RestaurantId].RemoveAll(o => o.OrderId == order.OrderId);
                        await BlobCache.InMemory.InsertObject<Dictionary<int, List<Order>>>(Configuration.CacheKeys.OrderHistory, history);
                    }
                    catch (NetworkException e)
                    {
                        throw new Exception("You must be online.", e);
                    }
                    catch (Exception e)
                    {
                        throw new Exception("Failed to delete order. Error:" + e.FullMessage(), e);
                    }
                }
            }
        }
        public void SetRestaurant(Restaurant rest)
        {
            const string UpdateOrderTxt = "Edit my order";
            const string NewOrderTxt = "I am ready!";
            const string NewOrderButtonColor = "#81C134";
            const string UpdateOrderColor = "#ED8413";

            Restaurant = rest;
            MenuUrl = Restaurant.GetMenuUrl();
            Title = Restaurant.RestaurantName;
            OrderButtonText = NewOrderTxt;
            OrderButtonColor = Color.FromHex(NewOrderButtonColor);
            OrderButtonEnabled = false;
            CurrentOrder = null;
            ExistingOrder = null;
            //fetch the orders
            Task.Run(async () =>
                {
                    ExistingOrder = await DomainManager.GetCurrentOrder();
                    var filtered = await DomainManager.GetHistory(Restaurant.RestaurantId);
                    var currentOrder = filtered.FirstOrDefault(o => o.AddDate.ToLocalTime().Date == DateTime.Today);
                    Device.BeginInvokeOnMainThread(() =>
                        {
                            var hasOrderForToday = currentOrder != null;
                            if (hasOrderForToday)
                            {
                                OrderButtonText = UpdateOrderTxt;
                                OrderButtonColor = Color.FromHex(UpdateOrderColor);
                                CurrentOrder = currentOrder;
                                currentOrder.IsCurrentOrder = true;
                            }
                            else
                            {
                                OrderButtonText = NewOrderTxt;
                                OrderButtonColor = Color.FromHex(NewOrderButtonColor);
                                CurrentOrder = new Order() { RestaurantId = this.Restaurant.RestaurantId };
                            }

                            PreviousOrders = new ObservableCollection<Order>(filtered);
                            OrderButtonEnabled = true;
                        });
                });
        }