private void RegisterClick(object sender, RoutedEventArgs e)
        {
            if (UsernameField.Text == "" || PasswordField.Password == "" || ConfirmPasswordField.Password == "")
            {
                ErrorField.Text = "All fields are mandatory.";
                return;
            }
            if (PasswordField.Password != ConfirmPasswordField.Password)
            {
                ErrorField.Text = "Password and Confirmation don't match.";
                return;
            }

            ErrorField.Text = "";

            APIRequest request = new APIRequest(APIRequest.POST, this, APIRequest.requestCodeType.Register, "register");

            Dictionary<string, string> dict = new Dictionary<string, string>()
            {
                {"username", UsernameField.Text},
                {"password", PasswordField.Password}
            };
            var serializer = new DataContractJsonSerializer(dict.GetType(), new DataContractJsonSerializerSettings()
            {
                UseSimpleDictionaryFormat = true
            });
            MemoryStream stream = new MemoryStream();
            serializer.WriteObject(stream, dict);
            byte[] bytes = stream.ToArray();
            string content = Encoding.UTF8.GetString(bytes, 0, bytes.Length);

            request.Execute(null, content);
        }
        public void onTaskCompleted(string result, APIRequest.requestCodeType requestCode)
        {
            if (result != null)
            {
                if (requestCode == APIRequest.requestCodeType.Register)
                {
                    JsonObject json = JsonObject.Parse(result);
                    if (!json.ContainsKey("error"))
                    {
                        Frame.Navigate(typeof(Login));
                        Frame.BackStack.Clear();
                    }
                    else
                    {
                        ErrorField.Text = json.GetNamedString("error");
                    }
                }
            }
            else
            {
                var toastXmlContent = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);

                var txtNodes = toastXmlContent.GetElementsByTagName("text");
                txtNodes[0].AppendChild(toastXmlContent.CreateTextNode("Server request failed."));
                txtNodes[1].AppendChild(toastXmlContent.CreateTextNode("Server is down or you lost internet connection."));

                var toast = new ToastNotification(toastXmlContent);
                var toastNotifier = ToastNotificationManager.CreateToastNotifier();
                toastNotifier.Show(toast);
            }
        }
        public void onTaskCompleted(string result, APIRequest.requestCodeType requestCode)
        {
            if (requestCode == APIRequest.requestCodeType.AllShares)
            {
                if (result != null)
                {
                    JsonArray json = JsonArray.Parse(result);

                    foreach (var share in json)
                    {
                        JsonObject shareObj = share.GetObject();
                        string symbol = shareObj.GetNamedString("symbol");
                        string name = shareObj.GetNamedString("name");
                        Quotation q = new Quotation() { Name = name, Symbol = symbol };
                        allItems.Add(q);
                    }
                }
            }
        }
        public void onTaskCompleted(string result, APIRequest.requestCodeType requestCode)
        {
            if (result != null)
            {
                if (requestCode == APIRequest.requestCodeType.Login)
                {
                    JsonObject json = JsonObject.Parse(result);
                    if (!json.ContainsKey("error"))
                    {
                        var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
                        JsonObject user = json.GetNamedObject("user");

                        localSettings.Values["token"] = json.GetNamedString("token");
                        if (user.GetNamedValue("main_share").ValueType != JsonValueType.Null)
                            localSettings.Values["main_share"] = user.GetNamedNumber("main_share");
                        localSettings.Values["username"] = user.GetNamedString("login");

                        Frame.Navigate(typeof (MainPage));
                        Frame.BackStack.Clear();
                    }
                    else
                    {
                        ErrorField.Text = json.GetNamedString("error");
                    }
                }
            }
            else
            {
                var toastXmlContent = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);

                var txtNodes = toastXmlContent.GetElementsByTagName("text");
                txtNodes[0].AppendChild(toastXmlContent.CreateTextNode("Server request failed."));
                txtNodes[1].AppendChild(toastXmlContent.CreateTextNode("Server is down or you lost internet connection."));

                var toast = new ToastNotification(toastXmlContent);
                var toastNotifier = ToastNotificationManager.CreateToastNotifier();
                toastNotifier.Show(toast);
            }
        }
        public async void UpdateChart()
        {

            string path = "share/evolution/" + Symbol;

            if (FromDate != null)
            {
                if (ToDate != null)
                {
                    if (FromDate.Value < ToDate.Value)
                    {
                        string fromDateString = FromDate.Value.ToString("yyyy-MM-dd");
                        string toDateString = ToDate.Value.ToString("yyyy-MM-dd");
                        path += "/" + fromDateString + "/" + toDateString;

                        if (ChartPeriodicity != null)
                            path += "/" + ChartPeriodicity;
                    }
                    else
                    {
                        var messageDialog = new MessageDialog("Invalid dates.");
                        
                        messageDialog.Commands.Add(new UICommand(
                            "Ok"));
                        
                        // Show the message dialog
                        await messageDialog.ShowAsync();
                    }
                }
            }

            

            APIRequest request = new APIRequest(APIRequest.GET, this, APIRequest.requestCodeType.ShareEvolution, path);
            request.Execute(null, null);

        }
        public void MainClick(object sender, RoutedEventArgs routedEventArgs)
        {
            if (Favorite == false)
            {
                APIRequest request = new APIRequest(APIRequest.POST, this, APIRequest.requestCodeType.Favorite, "portfolio/favorite");
                Dictionary<string, string> dict = new Dictionary<string, string>()
                {
                    {"symbol", Symbol}
                };
                var serializer = new DataContractJsonSerializer(dict.GetType(), new DataContractJsonSerializerSettings()
                {
                    UseSimpleDictionaryFormat = true
                });
                MemoryStream stream = new MemoryStream();
                serializer.WriteObject(stream, dict);
                byte[] bytes = stream.ToArray();
                string content = Encoding.UTF8.GetString(bytes, 0, bytes.Length);

                var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
                var token = localSettings.Values["token"];

                request.Execute((string) token, content);
            }
            else
            {
                APIRequest request = new APIRequest(APIRequest.POST, this, APIRequest.requestCodeType.Unfavorite, "portfolio/unfavorite");

                var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
                var token = localSettings.Values["token"];

                request.Execute((string)token, null);
            }

        }
        public void onTaskCompleted(string result, APIRequest.requestCodeType requestCode)
        {
            if (result != null)
            {
                if (requestCode == APIRequest.requestCodeType.Share)
                {
                    JsonObject json = new JsonObject();
                    JsonObject.TryParse(result, out json);
                    if (!json.ContainsKey("error"))
                    {
                        Name = json.GetNamedString("name");
                        Value = json.GetNamedNumber("value");
                        Time = json.GetNamedString("time");
                        Date = json.GetNamedString("date");
                        if (json.GetNamedValue("limit_down").ValueType != JsonValueType.Null)
                            LimitDown = json.GetNamedNumber("limit_down");
                        else
                            LimitDown = null;
                        if (json.GetNamedValue("limit_up").ValueType != JsonValueType.Null)
                            LimitUp = json.GetNamedNumber("limit_up");
                        else
                            LimitUp = null;
                        Favorite = Convert.ToBoolean(json.GetNamedNumber("is_main"));
                    }
                    else
                    {
                        if (NavigatePortfolio != null)
                            NavigatePortfolio();
                    }

                  

                }
                else if (requestCode == APIRequest.requestCodeType.ShareEvolution)
                {
                    ValuesEvolution.Clear();
                    Values2Evolution.Clear();

                    JsonArray json = JsonArray.Parse(result);
                    //var i = 0;
                    foreach (var point in json)
                    {
                        //i++;
                        JsonObject jsonPoint = JsonObject.Parse(point.Stringify());
                        string date = jsonPoint.GetNamedString("date");
                        //date = date.Substring(5, date.Length - 5);
                        double high = jsonPoint.GetNamedNumber("high");
                        double low = jsonPoint.GetNamedNumber("low");

                        var split = date.Split('-');
                        DateTime date2 = new DateTime(Int32.Parse(split[0]), Int32.Parse(split[1]), Int32.Parse(split[2]));
                        ValuesEvolution.Add(new Tuple<DateTime, double>(date2, low));
                        Values2Evolution.Add(new Tuple<DateTime, double>(date2, high));
                    }

                }
                else if (requestCode == APIRequest.requestCodeType.Favorite)
                {
                    JsonObject json = new JsonObject();
                    JsonObject.TryParse(result, out json);
                    if (!json.ContainsKey("error"))
                    {
                        Favorite = true;
                    }
                }
                else if (requestCode == APIRequest.requestCodeType.Unfavorite)
                {
                    JsonObject json = new JsonObject();
                    JsonObject.TryParse(result, out json);
                    if (!json.ContainsKey("error"))
                    {
                        Favorite = false;
                    }
                }
                else if (requestCode == APIRequest.requestCodeType.ClearLimitUp)
                {
                    JsonObject json = new JsonObject();
                    JsonObject.TryParse(result, out json);
                    if (!json.ContainsKey("error"))
                    {
                        LimitUp = null;
                    }
                }
                else if (requestCode == APIRequest.requestCodeType.ClearLimitDown)
                {
                    JsonObject json = new JsonObject();
                    JsonObject.TryParse(result, out json);
                    if (!json.ContainsKey("error"))
                    {
                        LimitDown = null;
                    }
                }else if (requestCode == APIRequest.requestCodeType.PortfolioRemove)
                {
                    JsonObject json = new JsonObject();
                    JsonObject.TryParse(result, out json);
                    if (!json.ContainsKey("error"))
                    {
                        if (NavigatePortfolio != null)
                            NavigatePortfolio();
                    }
                }
            }
            else
            {
                var toastXmlContent = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);

                var txtNodes = toastXmlContent.GetElementsByTagName("text");
                txtNodes[0].AppendChild(toastXmlContent.CreateTextNode("Server request failed."));
                txtNodes[1].AppendChild(toastXmlContent.CreateTextNode("Server is down or you lost internet connection."));

                var toast = new ToastNotification(toastXmlContent);
                var toastNotifier = ToastNotificationManager.CreateToastNotifier();
                toastNotifier.Show(toast);
            }

        }
        public void RefreshShare()
        {
            APIRequest request = new APIRequest(APIRequest.GET, this, APIRequest.requestCodeType.Share, "share/" + _symbol);
            var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
            var token = localSettings.Values["token"];
            request.Execute((string) token, null);

            UpdateChart();
        }
        public void Logout()
        {
            APIRequest request = new APIRequest(APIRequest.POST, this, APIRequest.requestCodeType.Logout, "logout");

            var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
            var token = localSettings.Values["token"];

            request.Execute((string)token, null);
        }
 private void LoadAllItems()
 {
     APIRequest request = new APIRequest(APIRequest.GET, this, APIRequest.requestCodeType.AllShares, "shares");
     request.Execute(null, null);
 }
        public void onTaskCompleted(string result, APIRequest.requestCodeType requestCode)
        {
            if (result != null)
            {
                if (requestCode == APIRequest.requestCodeType.SetLimit)
                {
                    JsonObject json = new JsonObject();
                    JsonObject.TryParse(result, out json);
                    if (!json.ContainsKey("error"))
                    {
                        if (NavigateBack != null)
                            NavigateBack();
                    }
                }
            }
            else
            {
                var toastXmlContent = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);

                var txtNodes = toastXmlContent.GetElementsByTagName("text");
                txtNodes[0].AppendChild(toastXmlContent.CreateTextNode("Server request failed."));
                txtNodes[1].AppendChild(toastXmlContent.CreateTextNode("Server is down or you lost internet connection."));

                var toast = new ToastNotification(toastXmlContent);
                var toastNotifier = ToastNotificationManager.CreateToastNotifier();
                toastNotifier.Show(toast);
            }
        }
        public void OkClick(object sender, RoutedEventArgs routedEventArgs)
        {
            string path = null;
            if (LimitType == LimitUpString)
            {
                path = "portfolio/setlimitup";
            }else if (LimitType == LimitDownString)
            {
                path = "portfolio/setlimitdown";
            }
            APIRequest request = new APIRequest(APIRequest.POST, this, APIRequest.requestCodeType.SetLimit, path);

            Dictionary<string, string> dict = new Dictionary<string, string>()
                {
                    {"symbol", Symbol},
                    {"limit", LimitValue.ToString("0.000", System.Globalization.CultureInfo.InvariantCulture)}
                };
            var serializer = new DataContractJsonSerializer(dict.GetType(), new DataContractJsonSerializerSettings()
            {
                UseSimpleDictionaryFormat = true
            });
            MemoryStream stream = new MemoryStream();
            serializer.WriteObject(stream, dict);
            byte[] bytes = stream.ToArray();
            string content = Encoding.UTF8.GetString(bytes, 0, bytes.Length);

            var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
            var token = localSettings.Values["token"];

            request.Execute((string)token, content);
        }
        public void onTaskCompleted(string result, APIRequest.requestCodeType requestCode)
        {
            if (result != null)
            {
                if (requestCode == APIRequest.requestCodeType.Portfolio)
                {
                    Items.Clear();

                    JsonArray json = JsonArray.Parse(result);

                    foreach (var share in json)
                    {
                        JsonObject shareObj = share.GetObject();
                        string symbol = shareObj.GetNamedString("symbol");
                        string name = shareObj.GetNamedString("name");
                        double value = shareObj.GetNamedNumber("value");
                        bool isMain = shareObj.GetNamedBoolean("is_main");
                        Quotation q = new Quotation() {Name = name, Symbol = symbol, Value = value, IsMain = isMain};
                        Items.Add(q);
                    }
                }
                else if (requestCode == APIRequest.requestCodeType.PortfolioAdd)
                {
                    RefreshPortfolio();
                }
                else if (requestCode == APIRequest.requestCodeType.UpdateUri)
                {
                    // update sucessfull
                }
                else if (requestCode == APIRequest.requestCodeType.Logout)
                {
                    JsonObject json = new JsonObject();
                    JsonObject.TryParse(result, out json);
                    view.LogoutHandler(!json.ContainsKey("error"));
                 
                }
            }
            else
            {
                var toastXmlContent = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);

                var txtNodes = toastXmlContent.GetElementsByTagName("text");
                txtNodes[0].AppendChild(toastXmlContent.CreateTextNode("Server request failed."));
                txtNodes[1].AppendChild(toastXmlContent.CreateTextNode("Server is down or you lost internet connection."));

                var toast = new ToastNotification(toastXmlContent);
                var toastNotifier = ToastNotificationManager.CreateToastNotifier();
                toastNotifier.Show(toast);
            }
        }
        async public void updateChannelUri()
        {
            PushNotificationChannel channel;
            try
            {
                //TODO subscribe to NetworkStatusChanged if channel is null
                channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
                string channelUri = channel.Uri;
                APIRequest request = new APIRequest(APIRequest.POST, this, APIRequest.requestCodeType.UpdateUri, "user/updatechannelUri");

                Dictionary<string, string> dict = new Dictionary<string, string>()
            {
                {"channelUri", channelUri}
            };
                var serializer = new DataContractJsonSerializer(dict.GetType(), new DataContractJsonSerializerSettings()
                {
                    UseSimpleDictionaryFormat = true
                });
                MemoryStream stream = new MemoryStream();
                serializer.WriteObject(stream, dict);
                byte[] bytes = stream.ToArray();
                string content = Encoding.UTF8.GetString(bytes, 0, bytes.Length);

                var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
                var token = localSettings.Values["token"];

                request.Execute((string)token, content);
            }

            catch (Exception ex)
            {
                var toastXmlContent = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);

                var txtNodes = toastXmlContent.GetElementsByTagName("text");
                txtNodes[0].AppendChild(toastXmlContent.CreateTextNode("Push notification service connection failed."));
                txtNodes[1].AppendChild(toastXmlContent.CreateTextNode(ex.Message));

                var toast = new ToastNotification(toastXmlContent);
                var toastNotifier = ToastNotificationManager.CreateToastNotifier();
                toastNotifier.Show(toast);
            }
             
        }
        public void ClearLimit(object sender, RoutedEventArgs routedEventArgs)
        {
            APIRequest request = null;

            if((string)((Button)sender).Tag == "ClearUp") 
                request = new APIRequest(APIRequest.POST, this, APIRequest.requestCodeType.ClearLimitUp, "portfolio/setlimitup");
            else if((string)((Button)sender).Tag == "ClearDown")
                request = new APIRequest(APIRequest.POST, this, APIRequest.requestCodeType.ClearLimitDown, "portfolio/setlimitdown");

            var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
            var token = localSettings.Values["token"];


            Dictionary<string, string> dict = new Dictionary<string, string>()
            {
                {"symbol", Symbol},
                {"limit", null}
            };
            var serializer = new DataContractJsonSerializer(dict.GetType(), new DataContractJsonSerializerSettings()
            {
                UseSimpleDictionaryFormat = true
            });
            MemoryStream stream = new MemoryStream();
            serializer.WriteObject(stream, dict);
            byte[] bytes = stream.ToArray();
            string content = Encoding.UTF8.GetString(bytes, 0, bytes.Length);

            request.Execute((string)token, content);
        }
        public void DeleteShare()
        {
            APIRequest request = request = new APIRequest(APIRequest.POST, this, APIRequest.requestCodeType.PortfolioRemove, "portfolio/remove");

            var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
            var token = localSettings.Values["token"];
            
            Dictionary<string, string> dict = new Dictionary<string, string>()
            {
                {"symbol", Symbol}
            };
            var serializer = new DataContractJsonSerializer(dict.GetType(), new DataContractJsonSerializerSettings()
            {
                UseSimpleDictionaryFormat = true
            });
            MemoryStream stream = new MemoryStream();
            serializer.WriteObject(stream, dict);
            byte[] bytes = stream.ToArray();
            string content = Encoding.UTF8.GetString(bytes, 0, bytes.Length);

            request.Execute((string)token, content);
        }
        public void RefreshPortfolio()
        {
            APIRequest request = new APIRequest(APIRequest.GET, this, APIRequest.requestCodeType.Portfolio, "portfolio");

            var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
            var token = localSettings.Values["token"];

            request.Execute((string) token, null);

        }