private void SendMessage(Models.Message message)
        {
            //sent messages to the server
            string apiUrl    = "https://ycandgap.me/api_server2.php";
            string apiMethod = "sendMessages";

            //Login_Request has two properties:username and password
            Login_Request mySendMessage_Request = new Login_Request();

            //get the login username from previow login page.
            mySendMessage_Request.message = message;

            // make http post request
            string response = Http.Post(apiUrl, new NameValueCollection()
            {
                { "api_method", apiMethod },
                { "api_data", JsonConvert.SerializeObject(mySendMessage_Request) }
            });
        }
        private void PreviousLoginActivity()
        {
            //Send the login username and password to the server and get response
            string apiUrl = "https://ycandgap.me/api_server2.php";
            string apiMethod = "loginUser";

            //Login_Request has two properties:username and password
            Login_Request myLogin_Request = new Login_Request();
            myLogin_Request.Username = username.Text;
            myLogin_Request.Password = password.Text.GetHashCode();

            // make http post request
            string response = Http.Post(apiUrl, new NameValueCollection()
            {
                { "api_method", apiMethod                                    },
                { "api_data",   JsonConvert.SerializeObject(myLogin_Request) }
            });

            // decode json string to dto object
            API_Response r = JsonConvert.DeserializeObject<API_Response>(response);

            // check response
            if (!r.IsError && r.ResponseData != null)
            {
                //**if login successfully, go to FriendsList page with the username
                ISharedPreferences sharedPref = PreferenceManager.GetDefaultSharedPreferences(this);
                ISharedPreferencesEditor editor = sharedPref.Edit();
                editor.PutString("RegistrationId", r.ResponseData);
                editor.Apply();
                var friendsActivity = new Intent(this, typeof(FriendsActivity));
                friendsActivity.PutExtra("UserRegisterID", r.ResponseData);
                StartActivity(typeof(FriendsActivity));
            }
            else
            {
                //if login fails, pop up an alert message. Wrong username or password or a new user
                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
                dialogBuilder.SetMessage(r.ErrorMessage);
                //dialogBuilder.SetPositiveButton("Ok", null);
                dialogBuilder.Show();
            }
        }
        public Models.Message[] GetMessages(ISharedPreferences sharedPref, User SelectedFriend, SessionStore sessionStore,
                                            PreKeyStore preKeyStore, SignedPreKeyStore signedPreKeyStore, IdentityKeyStore identityStore, SignalProtocolAddress SelectedFriendAddress)
        {
            // send the server the user name
            // server side does the selection and return the messages and store it in a message array.
            //Send the login username and password to the server and get response
            string apiUrl    = "https://ycandgap.me/api_server2.php";
            string apiMethod = "getMessage";

            //Login_Request has two properties:username and password
            Login_Request myLogin_Request = new Login_Request();

            Models.Message recieveMessage = new Models.Message();

            //get the login username from previow login page.
            recieveMessage.MessageReceiverRegisID = Convert.ToUInt32(sharedPref.GetString("RegistrationId", string.Empty));
            recieveMessage.MessageSenderRegisID   = SelectedFriend.RegisterationID;
            myLogin_Request.message = recieveMessage;
            UserID = myLogin_Request.RegistrationID;


            // make http post request
            string response = Http.Post(apiUrl, new NameValueCollection()
            {
                { "api_method", apiMethod },
                { "api_data", JsonConvert.SerializeObject(myLogin_Request) }
            });

            // decode json string to dto object
            API_Response2 r = JsonConvert.DeserializeObject <API_Response2>(response);

            // check response
            if (r != null)
            {
                if (!r.IsError && !string.IsNullOrEmpty(r.MessageText))
                {
                    SessionCipher sessionCipher = new SessionCipher(sessionStore, preKeyStore, signedPreKeyStore, identityStore, SelectedFriendAddress);
                    byte[]        decipherMessage;
                    if (!sessionStore.ContainsSession(SelectedFriendAddress))
                    {
                        decipherMessage = sessionCipher.decrypt(new PreKeySignalMessage((JsonConvert.DeserializeObject <byte[]>(r.MessageText))));
                    }
                    else
                    {
                        decipherMessage = sessionCipher.decrypt(new SignalMessage((JsonConvert.DeserializeObject <byte[]>(r.MessageText))));
                    }
                    string checkMessage = Encoding.UTF8.GetString(decipherMessage);

                    SelectedFriend.SelectedUserMessages.Add(new Models.Message
                    {
                        MessageID              = r.MessageID,
                        MessageSenderRegisID   = r.MessageSenderRegisID,
                        MessageReceiverRegisID = r.MessageReceiverRegisID,
                        MessageText            = checkMessage,
                        MessageTimestamp       = r.MessageTimestamp
                    });

                    return(SelectedFriend.SelectedUserMessages.ToArray());
                }
                else
                {
                    //if login fails, pop up an alert message. Wrong username or password or a new user
                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
                    if (!string.IsNullOrEmpty(r.ErrorMessage))
                    {
                        dialogBuilder.SetMessage(r.ErrorMessage);
                    }
                    else
                    {
                        dialogBuilder.SetMessage("No new messages");
                    }
                    //dialogBuilder.SetPositiveButton("Ok", null);
                    dialogBuilder.Show();
                    return(null);
                }
            }
            else
            {
                if (!sessionStore.ContainsSession(SelectedFriendAddress))
                {
                    // Instantiate a SessionBuilder for a remote recipientId + deviceId tuple.
                    SessionBuilder sessionBuilder = new SessionBuilder(sessionStore, preKeyStore, signedPreKeyStore,
                                                                       identityStore, SelectedFriendAddress);
                    RetrievedPreKey preKeyPublic = RetrieveSelectedFriendPublicPreKey(SelectedFriend);
                    IdentityKey     SelectedFriendSignedPreKey = new IdentityKey(JsonConvert.DeserializeObject <byte[]>(SelectedFriend.SignedPreKey), 0);
                    PreKeyBundle    retrievedPreKey            = new PreKeyBundle(SelectedFriend.RegisterationID, 1, preKeyPublic.PrekeyID, preKeyPublic.PublicPreKey.getPublicKey()
                                                                                  , SelectedFriend.SignedPreKeyID, SelectedFriendSignedPreKey.getPublicKey(), JsonConvert.DeserializeObject <byte[]>(SelectedFriend.SignedPreKeySignature)
                                                                                  , new IdentityKey(JsonConvert.DeserializeObject <byte[]>(SelectedFriend.IdentityKey), 0));
                    // Build a session with a PreKey retrieved from the server.
                    sessionBuilder.process(retrievedPreKey);
                }
                return(null);
            }
        }
        // Retrieve a list of conversations
        private User[] GetFriends()
        {
            // send the server the user name
            // server side does the selection and return the other users' names/id and store it in a user array.
            //Send the login username and password to the server and get response
            string apiUrl    = "https://ycandgap.me/api_server2.php";
            string apiMethod = "getFriends";

            //Login_Request has two properties:username and password
            Login_Request myLogin_Request = new Login_Request();
            //get the login username from previow login page.
            ISharedPreferences sharedPref = PreferenceManager.GetDefaultSharedPreferences(this);

            myLogin_Request.RegistrationID = Convert.ToUInt32(sharedPref.GetString("RegistrationId", string.Empty));


            // make http post request
            string response = Http.Post(apiUrl, new NameValueCollection()
            {
                { "api_method", apiMethod },
                { "api_data", JsonConvert.SerializeObject(myLogin_Request) }
            });

            // decode json string to dto object
            API_Response1 r = JsonConvert.DeserializeObject <API_Response1>(response);

            // check response
            if (r != null)
            {
                if (!r.IsError)
                {
                    if (r.Array != null)
                    {
                        MessagesActivity m           = new MessagesActivity();
                        List <User>      friends     = new List <User>();
                        string           lastmessage = string.Empty;
                        //(m.GetMessages(sharedPref) != null) ? m.GetMessages(sharedPref).FirstOrDefault().MessageText : string.Empty;
                        foreach (Friend friend in r.Array)
                        {
                            friends.Add(new User()
                            {
                                IdentityKey           = friend.IdentityKey,
                                LastMessage           = lastmessage,
                                RegisterationID       = Convert.ToUInt32(friend.RegistrationID),
                                SignedPreKeyID        = Convert.ToUInt32(friend.SignedPreKeyID),
                                SignedPreKeySignature = friend.SignedPreKeySignature,
                                SignedPreKey          = friend.SignedPreKey,
                                Username = friend.Username
                            });
                        }
                        return(friends.ToArray());
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    //if login fails, pop up an alert message. Wrong username or password or a new user
                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
                    dialogBuilder.SetMessage(r.ErrorMessage);
                    //dialogBuilder.SetPositiveButton("Ok", null);
                    dialogBuilder.Show();
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
        private void RequestRegister(uint registrationId, IdentityKeyPair identityKeyPair, SignedPreKeyRecord signedPreKey, List <PreKeyRecord> preKeys)
        {
            //Send the login username and password to the server and get response
            string apiUrl    = "https://ycandgap.me/api_server2.php";
            string apiMethod = "registerUser";

            // Login_Request has two properties: username and password
            Login_Request myLogin_Request = new Login_Request();

            myLogin_Request.Username                    = username.Text;
            myLogin_Request.Password                    = password.Text.GetHashCode();
            myLogin_Request.RegistrationID              = registrationId;
            myLogin_Request.PublicIdentityKey           = JsonConvert.SerializeObject(identityKeyPair.getPublicKey().serialize());
            myLogin_Request.PublicSignedPreKeyID        = signedPreKey.getId();
            myLogin_Request.PublicSignedPreKeySignature = JsonConvert.SerializeObject(signedPreKey.getSignature());
            myLogin_Request.PublicSignedPreKey          = JsonConvert.SerializeObject(signedPreKey.getKeyPair().getPublicKey().serialize());

            // Save in local Database
            ISharedPreferences       sharedprefs = PreferenceManager.GetDefaultSharedPreferences(this);
            ISharedPreferencesEditor editor      = sharedprefs.Edit();

            // Store identityKeyPair somewhere durable and safe.
            editor.PutString("IdentityKeyPair", JsonConvert.SerializeObject(identityKeyPair.serialize()));
            editor.PutString("SignedPreKey", JsonConvert.SerializeObject(signedPreKey.serialize()));
            editor.PutString("Username", username.Text);
            editor.PutInt("Password", password.Text.GetHashCode());

            // Store registrationId somewhere durable and safe.
            editor.PutString("RegistrationId", registrationId.ToString());
            editor.Apply();

            // make http post request
            string response = Http.Post(apiUrl, new NameValueCollection()
            {
                { "api_method", apiMethod },
                { "api_data", JsonConvert.SerializeObject(myLogin_Request) }
            });

            // decode json string to dto object
            API_Response r = JsonConvert.DeserializeObject <API_Response>(response);

            if (r != null)
            {
                if (!r.IsError)
                {
                    foreach (PreKeyRecord preKey in preKeys)
                    {
                        Prekey_Request preKey_Request = new Prekey_Request();
                        preKey_Request.PublicSignedPreKeyID = signedPreKey.getId();
                        preKey_Request.PublicPreKeyID       = preKey.getId();
                        preKey_Request.PublicPreKey         = JsonConvert.SerializeObject(preKey.getKeyPair().getPublicKey().serialize());
                        apiMethod = "storePreKeys";

                        // make http post request
                        string preKeyResponse = Http.Post(apiUrl, new NameValueCollection()
                        {
                            { "api_method", apiMethod },
                            { "api_data", JsonConvert.SerializeObject(preKey_Request) }
                        });

                        // decode json string to dto object
                        API_Response preKeyR = JsonConvert.DeserializeObject <API_Response>(preKeyResponse);
                        if (preKeyR == null)
                        {
                            break;
                        }
                    }
                }
            }
        }