package epson.print.storage.onedrive;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.Button;

import com.epson.iprint.storage.StorageProcessActivity;
import com.epson.iprint.storage.StorageProcessUploadActivity;
import com.epson.iprint.storage.StorageServiceClient;
import com.onedrive.sdk.extensions.IOneDriveClient;

import epson.print.R;
import epson.print.storage.StorageProcessUploadActivity;


public class OneDriveStorageProcessUploadActivity extends StorageProcessUploadActivity {
    protected static final String TAG = "OneDriveStorageProcessUploadActivity";
    boolean mExpired;
    private OneDriveClient mStorageServiceClient;

    protected void onStart() {
        super.onStart();
        mExpired = false;
        checkSession();
    }

    protected void onResume() {
        super.onResume();
        mExpired = false;
        OneDriveClient oneDriveClient = mStorageServiceClient;
        if (oneDriveClient != null && oneDriveClient.getUploadProcessError().equals(StorageServiceClient.ProcessError.RETRY)) {
            mExpired = true;
            checkSession();
        }
    }

    private void checkSession() {
        if (isConnected()) {
            mStorageServiceClient = (OneDriveClient) getStorageClient();
            if (mStorageServiceClient.isSignedIn(this) && mStorageServiceClient.isSessionExpired()) {
                new Thread() {
                    public void run() {
                        super.run();
                        mStorageServiceClient.getOneDriveClient(this, new OneDriveAuthenticator.OnOneDriveAuthenticatorListener() {
                            public void onNotifyOneDriveClient(IOneDriveClient iOneDriveClient) {
                                findViewById(R.id.folder_content_layout_for_upload).setVisibility(View.VISIBLE);
                                if (iOneDriveClient == null) {
                                    mStorageServiceClient.revokeSignedInData(this);
                                    updateSignInStatus();
                                } else if (mExpired) {
                                    mExpired = false;
                                    mStorageServiceClient.resetUploadProcessError();
                                    ((Button) findViewById(R.id.save_button)).performClick();
                                }
                            }
                        });
                    }
                }.start();
                findViewById(R.id.folder_content_layout_for_upload).setVisibility(4);
            }
        }
    }

    public static Intent getProcessIntent(Context context, String str, StorageProcessActivity.ProcessType processType) {
        Intent intent = new Intent(context, OneDriveStorageProcessUploadActivity.class);
        setCommonExtra(intent, str);
        return intent;
    }
}
