package de.sebse.fuplanner.services.fulogin;

import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;

import org.jetbrains.annotations.NotNull;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

import androidx.annotation.Nullable;
import de.sebse.fuplanner.R;
import de.sebse.fuplanner.services.kvv.sync.Login;
import de.sebse.fuplanner.services.kvv.types.LoginToken;
import de.sebse.fuplanner.tools.logging.Logger;


/**
 * Represents an asynchronous login/registration task used to authenticate
 * the user.
 */
public class UserLoginTask extends AsyncTask<Void, Void, String> {

    /**
     * A dummy authentication store containing known user names and passwords.
     * TODO: remove after connecting to a real authentication system.
     */
    /*private static final String[] DUMMY_CREDENTIALS = new String[]{
            "foo@example.com:hello", "bar@example.com:world"
    };*/
    static final String PARAM_USER_PASS = "PARAM_USER_PASS";

    private final String mEmail;
    private final String mPassword;
    private final Login mVolleyLogin;
    private String mTokenType;
    private Logger log = new Logger(this);
    @SuppressLint("StaticFieldLeak")
    @Nullable
    private FUAuthenticatorActivity mActivity;

    UserLoginTask(String email, String password, String tokenType, @NotNull Context context) {
        mEmail = email;
        mPassword = password;
        mTokenType = tokenType;
        mVolleyLogin = new Login(context);
        if (context instanceof FUAuthenticatorActivity)
            mActivity = (FUAuthenticatorActivity) context;
    }

    @Override
    protected String doInBackground(Void... params) {
        // TODO: attempt authentication against a network service.

        CountDownLatch latch = new CountDownLatch(1);
        AtomicReference<LoginToken> login = new AtomicReference<>();
        mVolleyLogin.doLogin(mEmail, mPassword, success -> {
            mVolleyLogin.testLoginToken(success, success1 -> {
                login.set(success);
                latch.countDown();
            }, error -> {
                log.e(error);
                latch.countDown();
            });
        }, error -> {
            log.e(error);
            latch.countDown();
        });
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (login.get() == null) {
            return null;
        } else {
            return login.get().toJsonString();
        }

        /*for (String credential : DUMMY_CREDENTIALS) {
            String[] pieces = credential.split(":");
            if (pieces[0].equals(mEmail)) {
                // Account exists, return true if the password matches.
                return pieces[1].equals(mPassword) ? "auth token here" : null;
            }
        }

        // TODO: register the new account here.
        return null;*/
    }

    @Override
    protected void onPostExecute(final String success) {
        if (mActivity == null || mActivity.isFinishing())
            return;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mActivity.isDestroyed())
            return;
        mActivity.mAuthTask = null;
        mActivity.showProgress(false);

        if (success != null) {
            final Intent res = new Intent();
            res.putExtra(AccountManager.KEY_ACCOUNT_NAME, mEmail);
            res.putExtra(AccountManager.KEY_ACCOUNT_TYPE, AccountGeneral.ACCOUNT_TYPE);
            res.putExtra(AccountManager.KEY_AUTHTOKEN, success);
            res.putExtra(PARAM_USER_PASS, mPassword);
            mActivity.finishLogin(res);
        } else {
            mActivity.mPasswordView.setError(mActivity.getString(R.string.error_incorrect_password));
            mActivity.mPasswordView.requestFocus();
        }
    }

    @Override
    protected void onCancelled() {
        if (mActivity == null || mActivity.isFinishing())
            return;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mActivity.isDestroyed())
            return;
        mActivity.mAuthTask = null;
        mActivity.showProgress(false);
    }
}