/*
 * Copyright 2016 Realm Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.realm.examples.securetokenandroidkeystore;

import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import com.example.securetokenandroidkeystore.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.security.KeyStoreException;
import java.util.UUID;

import io.realm.Realm;
import io.realm.SyncConfiguration;
import io.realm.SyncManager;
import io.realm.SyncUser;
import io.realm.android.SecureUserStore;
import io.realm.internal.objectserver.Token;

/**
 * Activity responsible of unlocking the KeyStore
 * before using the {@link io.realm.android.SecureUserStore} to encrypt
 * the Token we get from the session
 */
public class MainActivity extends AppCompatActivity {
    private TextView txtKeystoreState;

    private SecureUserStore secureUserStore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtKeystoreState = (TextView) findViewById(R.id.txtLabelKeyStore);

        try {
            secureUserStore = new SecureUserStore(this);
            SyncManager.setUserStore(secureUserStore);

            if (secureUserStore.isKeystoreUnlocked()) {
                buildSyncConf();
                keystoreUnlockedMessage();
            } else {
                secureUserStore.unlockKeystore();
            }
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            // We return to the app after the KeyStore is unlocked or not.
            if (secureUserStore.isKeystoreUnlocked()) {
                buildSyncConf();
                keystoreUnlockedMessage();
            } else {
                keystoreLockedMessage();
            }
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
    }

    // build SyncConfiguration with a user store to store encrypted Token.
    private void buildSyncConf() {
        // the rest of Sync logic ...
        SyncUser user = createTestUser(Long.MAX_VALUE);
        String url = "realm://objectserver.realm.io/default";
        SyncConfiguration secureConfig = new SyncConfiguration.Builder(user, url).build();
        Realm realm = Realm.getInstance(secureConfig);
        // ...
    }

    // Helpers
    private final static String USER_TOKEN = UUID.randomUUID().toString();

    private static SyncUser createTestUser(long expires) {
        Token userToken = new Token(USER_TOKEN, "JohnDoe", null, expires, null);
        JSONObject obj = new JSONObject();
        try {
            JSONObject realmDesc = new JSONObject();
            realmDesc.put("uri", "realm://objectserver.realm.io/default");

            obj.put("authUrl", "http://objectserver.realm.io/auth");
            obj.put("userToken", userToken.toJson());
            return SyncUser.fromJson(obj.toString());
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    private void keystoreLockedMessage() {
        txtKeystoreState.setBackgroundColor(ContextCompat.getColor(this, R.color.colorLocked));
        txtKeystoreState.setText(R.string.locked_text);
    }

    private void keystoreUnlockedMessage() {
        txtKeystoreState.setBackgroundColor(ContextCompat.getColor(this, R.color.colorActivated));
        txtKeystoreState.setText(R.string.unlocked_text);
    }
}


@@ -850,68 +850,8 @@
 R;%0A%0A
-import org.json.JSONException;%0Aimport org.json.JSONObject;%0A%0A
 impo
@@ -890,31 +890,43 @@
 on;%0A
+%0A
 import 
-java.util.UUID;%0A
+io.realm.ObjectServerError;
 %0Aimp
@@ -980,16 +980,49 @@
 ration;%0A
+import io.realm.SyncCredentials;%0A
 import i
@@ -1112,53 +1112,8 @@
 ore;
-%0Aimport io.realm.internal.objectserver.Token;
 %0A%0A/*
@@ -2713,49 +2713,89 @@
 Sync
-User user = createTestUser(Long.MAX_VALUE
+Credentials credentials = SyncCredentials.usernamePassword(%22username%22, %22password%22
 );%0A 
@@ -2801,16 +2801,22 @@
         
+final 
 String u
@@ -2821,17 +2821,20 @@
  url
- = %22realm
+Auth = %22http
 ://o
@@ -2853,24 +2853,26 @@
 realm.io
-/default
+:9080/auth
 %22;%0A     
@@ -2878,585 +2878,390 @@
     
-SyncConfiguration secureConfig = new SyncConfiguration.Builder(user, url).build();%0A        Realm realm = Realm.getInstance(secureConfig);%0A        // ...%0A    %7D%0A%0A    // Helpers%0A    private final static String USER_TOKEN = UUID.randomUUID().toString();%0A%0A    private static SyncUser createTestUser(long expires) %7B%0A        Token userToken = new Token(USER_TOKEN, %22JohnDoe%22, null, expires, null);%0A        JSONObject obj = new JSONObject();%0A        try %7B%0A            JSONObject realmDesc = new JSONObject();%0A            realmDesc.put(%22uri%22, %22realm://objectserver.realm.io/default%22
+final String url = %22realm://objectserver.realm.io/default%22;%0A%0A        SyncUser.loginAsync(credentials, urlAuth, new SyncUser.Callback%3CSyncUser%3E() %7B%0A            @Override%0A            public void onSuccess(SyncUser user) %7B%0A                SyncConfiguration secureConfig = new SyncConfiguration.Builder(user, url).build();%0A                Realm realm = Realm.getInstance(secureConfig
 );%0A
-%0A
     
@@ -3272,251 +3272,115 @@
     
-obj.put(%22authUrl%22, %22http://objectserver.realm.io/auth%22);%0A            obj.put(%22userToken%22, userToken.toJson());%0A            return SyncUser.fromJson(obj.toString());%0A        %7D catch (JSONException e) %7B%0A            throw new RuntimeException(e);
+    // ...%0A            %7D%0A%0A            @Override%0A            public void onError(ObjectServerError error) %7B%7D
 %0A   
@@ -3377,32 +3377,34 @@
 or) %7B%7D%0A        %7D
+);
 %0A    %7D%0A%0A    priv

fix secureTokenAndroidKeyStore example to pass monkey test (#5477)