package com.epson.iprint.storage.dropbox;

import android.content.Context;


import com.dropbox.core.android.Auth;
import com.dropbox.core.p005v2.DbxClientV2;
import com.epson.iprint.storage.SecureKeyStore;
import com.epson.iprint.storage.StorageSecureStore;
import epson.server.utils.Define;

public class DropboxV2Adapter {
    public static void init(@NonNull Context context) {
        String savedToken = getSavedToken(context);
        if (savedToken != null) {
            DropboxClientFactory.init(savedToken);
        }
    }

    public static void getTokenAndInitClient(@NonNull Context context) {
        String oAuth2Token = Auth.getOAuth2Token();
        if (oAuth2Token != null) {
            StorageSecureStore.getSharedSecureStore().put(Define.DROPBOX_V2_TOKEN, oAuth2Token, StorageSecureStore.EXEC_MODE.OVERWRITE_IF_EXIST);
            eraseOldData();
            DropboxClientFactory.init(oAuth2Token);
        }
    }

    private static void eraseOldData() {
        StorageSecureStore sharedSecureStore = StorageSecureStore.getSharedSecureStore();
        for (String revoke : new String[]{Define.DROPBOX_ACCESS_KEY, Define.DROPBOX_ACCESS_SECRET, Define.DROPBOX_PASSWORD, Define.DROPBOX_USERNAME}) {
            sharedSecureStore.revoke(revoke);
        }
    }

    public static boolean hasToken(@NonNull Context context) {
        return getSavedToken(context) != null;
    }

    private static String getSavedToken(@NonNull Context context) {
        return StorageSecureStore.getSharedSecureStore().fetch(Define.DROPBOX_V2_TOKEN);
    }

    public static void startAuthentication(@NonNull Context context) {
        Auth.startOAuth2Authentication(context, new SecureKeyStore().getApiKeyA(context));
    }

    @Nullable
    public static DbxClientV2 getClient() {
        return DropboxClientFactory.getClient();
    }

    public static void clearToken(@NonNull Context context) {
        StorageSecureStore.getSharedSecureStore().revoke(Define.DROPBOX_V2_TOKEN);
        DropboxClientFactory.deleteClient();
    }
}
