package co.pixelbeard.theanfieldwrap.devices;

import android.content.Context;
import android.os.Handler;
import android.util.Log;

import java.util.List;

import co.pixelbeard.theanfieldwrap.data.Device;
import co.pixelbeard.theanfieldwrap.data.responses.GenericResponse;
import co.pixelbeard.theanfieldwrap.data.responses.GetDevicesResponse;
import co.pixelbeard.theanfieldwrap.data.source.DataRepository;
import co.pixelbeard.theanfieldwrap.networking.CallbackWrapper;
import co.pixelbeard.theanfieldwrap.utils.PrefKey;
import co.pixelbeard.theanfieldwrap.utils.PrefUtils;
import co.pixelbeard.theanfieldwrap.utils.TawController;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class DevicesPresenter implements DevicesContract.Presenter {


    private DevicesContract.View mView;
    private DataRepository mRepo;

    public DevicesPresenter(DevicesContract.View view, DataRepository repo) {
        if (view != null && repo != null) {
            this.mView = view;
            this.mRepo = repo;

            mView.setPresenter(this);
        } else {
            throw new RuntimeException();
        }
    }


    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {

    }

    @Override
    public void clearUserData(Context context) {
        //TODO test this
//        mRepo.clearAllData(context);
        mRepo.logout().subscribe(new Observer<GenericResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(GenericResponse genericResponse) {
                Log.d("LOGOUT", genericResponse.getMessage());
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

    }

    @Override
    public void getDevices(List<Device> devices) {
        if (devices != null) {//&& !PrefUtils.getInstance().getBooleanPref(PrefKey.LOGGED_IN)) {
            mView.setDevicesAdapter(devices);
        } else {
            if (mView != null && mView.checkConnection()) {
                mRepo.getActiveDevices().subscribe(new CallbackWrapper<GetDevicesResponse>(mView) {
                    @Override
                    protected void onSuccess(GetDevicesResponse getDevicesResponse) {

                        String id = TawController.getUniqueId();

                        List<Device> apiDevices = getDevicesResponse.getDevices();

                        for (int i = 0; i < apiDevices.size(); i++) {

                            Device device = apiDevices.get(i);

                            if (device.getUniqueDeviceId().equals(id)) {
                                apiDevices.remove(i);
                                apiDevices.add(0, device);
                                break;
                            }
                        }

                        if (mView != null) {
                            mView.setDevicesAdapter(apiDevices);
                        }
                    }

                    @Override
                    protected void onSuccessFalse(GetDevicesResponse getDevicesResponse) {
                        mView.showSingleButtonDialog("Error", getDevicesResponse.getMessage());
                    }
                });
            } else {
                if (mView != null) {
                    mView.hideLoader();
                    mView.onConnectionError();
                }
            }
        }
    }

    @Override
    public void unlinkDevice(Device device, int position) {

        String apiToken;

        if (PrefUtils.getInstance().getBooleanPref(PrefKey.LOGGED_IN)) {
            apiToken = PrefUtils.getInstance().getStringPref(PrefKey.AUTH_TOKEN);
        } else {
            apiToken = device.getUserAuthToken();
        }

        if (mView != null && mView.checkConnection()) {
            mView.showLoader("Unlinking " + device.getDeviceName() + " from your account");
            mRepo.unlinkDevice(apiToken, device.getId()).subscribe(new CallbackWrapper<GenericResponse>(mView) {
                @Override
                protected void onSuccess(GenericResponse genericResponse) {
                    new Handler().postDelayed(() -> {
                        if (PrefUtils.getInstance().getBooleanPref(PrefKey.LOGGED_IN)) {
                            mView.removeItemFromAdapter(position);
                        } else {
                            mView.finishDevicesActivityWithUnlinkedResult();
                        }

                    }, 200);
                }

                @Override
                protected void onSuccessFalse(GenericResponse genericResponse) {
                    new Handler().postDelayed(() -> {
                        if (mView != null) {
                            mView.showSingleButtonDialog("Error", genericResponse.getMessage());
                        }
                    }, 200);
                }
            });
        } else {
            if (mView != null) {
                mView.onConnectionError();
            }
        }
    }
}
