package epson.print.storage.gdrivev3;


import com.epson.iprint.storage.Network;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

public class GoogleDownloadPresenter implements GoogleDownloadContract.UserActionListener, IprintGoogleSignIn.SignInListener, DriveListTask.ListTaskCompleteListener, DownloadTask.DownloadCompleteListener, PlayServiceDialogManager.SingInCancelNotifier {
    private final WeakReference<GoogleDownloadContract.View> mDownloadViewReference;
    private final DownloaderWrapper mGoogleDownloader;
    private final IprintGoogleSignIn mIprintGoogleSignIn;
    private boolean mIsDownloading = false;
    private final Network mMisc;
    private final PlayServiceDialogManager mPlayServiceDialogManager;
    private SignInState mSignInStatus;
    private boolean mStartListDone;
    private TaskState mTaskRunning;

    private enum SignInState {
        SIGN_IN,
        SIGN_OUT
    }

    private enum TaskState {
        RUNNING,
        STOP
    }

    private enum TaskType {
        FILE_LIST,
        DOWNLOAD
    }

    public GoogleDownloadPresenter(@NonNull IprintGoogleSignIn iprintGoogleSignIn, @NonNull PlayServiceDialogManager playServiceDialogManager, @NonNull DownloaderWrapper downloaderWrapper, @NonNull Network network, @NonNull GoogleDownloadContract.View view) {
        mIprintGoogleSignIn = iprintGoogleSignIn;
        mPlayServiceDialogManager = playServiceDialogManager;
        mGoogleDownloader = downloaderWrapper;
        mMisc = network;
        mDownloadViewReference = new WeakReference<>(view);
        mSignInStatus = SignInState.SIGN_OUT;
        mStartListDone = false;
        mTaskRunning = TaskState.STOP;
    }

    @Nullable
    private GoogleDownloadContract.View getDownloadView() {
        return (GoogleDownloadContract.View) mDownloadViewReference.get();
    }

    public void initView() {
        GoogleDownloadContract.View downloadView = getDownloadView();
        if (downloadView != null) {
            changeSignInStatus(downloadView, SignInState.SIGN_OUT);
            downloadView.setSignInButtonEnabled(false);
            downloadView.dismissProgress();
        }
    }

    public void activityOnResume() {
        GoogleDownloadContract.View downloadView = getDownloadView();
        if (downloadView != null) {
            mMisc.selectSimpleAp(downloadView.getActivityWrapper(), false);
            if (!mMisc.isOnline(downloadView.getActivityWrapper())) {
                downloadView.showOfflineErrorDialog();
            } else if (!mPlayServiceDialogManager.checkPlayService(downloadView.getActivityWrapper(), this) && mTaskRunning == TaskState.STOP) {
                downloadView.setSignInButtonEnabled(true);
                if (mIprintGoogleSignIn.isSignInValid(downloadView.getActivityWrapper().getActivity(), IprintGoogleSignIn.OperationType.DOWNLOAD)) {
                    changeSignInStatus(downloadView, SignInState.SIGN_IN);
                    if (!mStartListDone) {
                        start1stListTask(downloadView, mIprintGoogleSignIn.getSignInAccount(downloadView.getActivityWrapper().getActivity()));
                        return;
                    }
                    return;
                }
                changeSignInStatus(downloadView, SignInState.SIGN_OUT);
            }
        }
    }

    public void activityOnPause() {
        mPlayServiceDialogManager.onActivityPaused();
    }

    public boolean isDownloading() {
        return mIsDownloading;
    }

    public void playServiceInstallCancel() {
        GoogleDownloadContract.View downloadView = getDownloadView();
        if (downloadView != null) {
            downloadView.setSignInButtonEnabled(true);
            downloadView.showSignInFailDialog();
        }
    }

    public void signInOrDisconnectClicked() {
        GoogleDownloadContract.View downloadView = getDownloadView();
        if (downloadView != null) {
            downloadView.setSignInButtonEnabled(false);
            if (mSignInStatus == SignInState.SIGN_IN) {
                mIprintGoogleSignIn.disconnectAccount(downloadView.getActivityWrapper(), this);
            } else {
                mIprintGoogleSignIn.startSignIn(this, downloadView.getActivityWrapper(), IprintGoogleSignIn.OperationType.DOWNLOAD);
            }
        }
    }

    public void onSignInComplete(boolean z, GoogleSignInAccount googleSignInAccount) {
        GoogleDownloadContract.View downloadView = getDownloadView();
        if (downloadView != null) {
            downloadView.clearListItems();
            changeSignInStatus(downloadView, z ? SignInState.SIGN_IN : SignInState.SIGN_OUT);
            if (!z) {
                downloadView.setSignInButtonEnabled(true);
                downloadView.dismissProgress();
                downloadView.showSignInFailDialog();
            } else if (googleSignInAccount != null) {
                start1stListTask(downloadView, googleSignInAccount);
            } else {
                throw new IllegalStateException();
            }
        }
    }

    public void onAddScopeCompleted(boolean z) {
        GoogleDownloadContract.View downloadView = getDownloadView();
        if (downloadView != null) {
            onSignInComplete(z, z ? mIprintGoogleSignIn.getSignInAccount(downloadView.getActivityWrapper().getActivity()) : null);
        }
    }

    public void onDisconnectCompleted() {
        GoogleDownloadContract.View downloadView = getDownloadView();
        if (downloadView != null) {
            mGoogleDownloader.invalidateDownloader();
            changeSignInStatus(downloadView, SignInState.SIGN_OUT);
            downloadView.setSignInButtonEnabled(true);
            downloadView.clearListItems();
        }
    }

    private void start1stListTask(GoogleDownloadContract.View view, @Nullable GoogleSignInAccount googleSignInAccount) {
        if (googleSignInAccount != null) {
            mGoogleDownloader.createDownloader(view.getActivityWrapper(), googleSignInAccount);
            startListTask((OnlineFile) null);
            return;
        }
        throw new IllegalStateException();
    }

    public void startListTask(@Nullable OnlineFile onlineFile) {
        GoogleDownloadContract.View downloadView = getDownloadView();
        if (downloadView != null) {
            onTaskStart(downloadView, TaskType.FILE_LIST);
            mStartListDone = true;
            mGoogleDownloader.startListTask(onlineFile, this);
        }
    }

    private void changeSignInStatus(GoogleDownloadContract.View view, SignInState signInState) {
        mSignInStatus = signInState;
        view.changeSignInOutButton(signInState == SignInState.SIGN_IN ? 1 : 0);
    }

    public void listComplete(ArrayList<OnlineFile> arrayList) {
        GoogleDownloadContract.View downloadView = getDownloadView();
        if (downloadView != null) {
            onTaskEnd(downloadView);
            downloadView.listFiles(arrayList);
        }
    }

    public void itemSelected(@NonNull OnlineFile onlineFile) {
        GoogleDownloadContract.View downloadView = getDownloadView();
        if (downloadView != null) {
            if (!mGoogleDownloader.isDownloadValid()) {
                throw new IllegalStateException();
            } else if (onlineFile.isFolder()) {
                startListTask(onlineFile);
            } else {
                onTaskStart(downloadView, TaskType.DOWNLOAD);
                mIsDownloading = true;
                mGoogleDownloader.startDownload(downloadView.getActivityWrapper(), onlineFile, this);
            }
        }
    }

    public void backKeyPressed() {
        GoogleDownloadContract.View downloadView = getDownloadView();
        if (downloadView != null) {
            if (mSignInStatus != SignInState.SIGN_IN) {
                downloadView.finishActivity();
            } else if (!mGoogleDownloader.isDownloadValid()) {
                throw new IllegalStateException();
            } else if (mGoogleDownloader.isRootFolder()) {
                downloadView.finishActivity();
            } else {
                startListTask(new ParentFolder());
            }
        }
    }

    public void cancelDownload() {
        mGoogleDownloader.cancelDownload();
    }

    public void onPreviewActivityEnd() {
        mGoogleDownloader.onDownloadPreviewEnd();
    }

    public void onDownloadComplete(boolean z, @Nullable String str) {
        GoogleDownloadContract.View downloadView = getDownloadView();
        mIsDownloading = false;
        if (downloadView != null) {
            onTaskEnd(downloadView);
            if (str != null) {
                downloadView.startPreviewActivity(str);
            } else if (z) {
                downloadView.showDownloadErrorDialog();
            }
        }
    }

    private void onTaskEnd(GoogleDownloadContract.View view) {
        mTaskRunning = TaskState.STOP;
        view.dismissProgress();
        view.setSignInButtonEnabled(true);
    }

    private void onTaskStart(GoogleDownloadContract.View view, TaskType taskType) {
        mTaskRunning = TaskState.RUNNING;
        if (taskType == TaskType.DOWNLOAD) {
            view.showDownloadProgress();
        } else {
            view.showProgress();
        }
        view.setSignInButtonEnabled(false);
    }
}
