package co.pixelbeard.theanfieldwrap.home;

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

import com.onesignal.OneSignal;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import co.pixelbeard.theanfieldwrap.data.NotificationSetting;
import co.pixelbeard.theanfieldwrap.data.responses.GenericResponse;
import co.pixelbeard.theanfieldwrap.data.responses.GetWalletResponse;
import co.pixelbeard.theanfieldwrap.data.responses.NotificationSettingsResponse;
import co.pixelbeard.theanfieldwrap.data.responses.SubscriptionItemResponse;
import co.pixelbeard.theanfieldwrap.data.source.DataRepository;
import co.pixelbeard.theanfieldwrap.data.source.DataSource;
import co.pixelbeard.theanfieldwrap.freeSubscription.ActiveSubscriptionResponse;
import co.pixelbeard.theanfieldwrap.networking.CallbackWrapper;
import co.pixelbeard.theanfieldwrap.utils.PrefKey;
import co.pixelbeard.theanfieldwrap.utils.PrefUtils;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by Michael Stoddart
 * 29/12/2018.
 */
public class HomePresenter implements HomeContract.Presenter {

    private HomeContract.View mView;
    private DataRepository mRepo;

    public HomePresenter(HomeContract.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() {
        if (mView != null && mView.checkConnection()) {
            mRepo.getUserSettings().subscribe(new CallbackWrapper<NotificationSettingsResponse>(mView) {
                @Override
                protected void onSuccess(NotificationSettingsResponse notificationSettingsResponse) {
                    mRepo.saveUserSettings(notificationSettingsResponse.getSettings());
                }

                @Override
                protected void onSuccessFalse(NotificationSettingsResponse notificationSettingsResponse) {

                }
            });
        } else {
            if (mView != null) {
                mView.onConnectionError();
            }
        }

    }

    @Override
    public void unsubscribe() {

    }

    @Override
    public void clearUserData(Context context) {


    }

    @Override
    public void podcastsClicked() {
        mView.setPodcastsFrag();
    }

    @Override
    public void videosClicked() {
        mView.setVideosFrag();
    }

    @Override
    public void writingClicked() {
        mView.setWritingFrag();
    }

    @Override
    public void profileClicked() {
        mView.setProfileFrag();
    }

    @Override
    public void recordAnalytic(String type, String variable, String secondVar) {
        mRepo.recordAnalytic(type, variable, secondVar).subscribe(new Observer<GenericResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(GenericResponse genericResponse) {
                if (genericResponse != null) {
                    Log.d("ANALYTIC: " + type, genericResponse.getMessage());
                }
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    public void creditAccount(int value, String title, String purchaseToken) {
        if (mView != null && mView.checkConnection()) {
            mRepo.creditUserAccount(value, title, purchaseToken).subscribe(new CallbackWrapper<GetWalletResponse>(mView) {
                @Override
                protected void onSuccess(GetWalletResponse getWalletResponse) {
                    PrefUtils.getInstance().putIntPref(PrefKey.TOKEN_BALANCE, getWalletResponse.getWallet().getBalance());
                    if (mView != null) {
                        mView.consumeToken(purchaseToken);
                    }
                }

                @Override
                protected void onSuccessFalse(GetWalletResponse getWalletResponse) {
                    //Ignore, retry on next load or wallet page
                }
            });
        }
    }

    @Override
    public void checkPodcastStatesForUserId(long userId) {
        mRepo.getPodcastStates((podcastState, position) -> {
            if (podcastState != null && podcastState.getUserId() != userId) {
                clearPodcastStates();
            }
        });
    }

    @Override
    public void checkDownloadsForUserId(long userId, Context context) {
        mRepo.getDownloadedPodcasts(podcasts -> {
            if (podcasts != null && podcasts.size() > 0) {

                long prevLoggedIn = PrefUtils.getInstance().getLongPref(PrefKey.PREV_LOGGED_IN_USER_ID);
                long currentUserId = PrefUtils.getInstance().getLongPref(PrefKey.USER_ID);


                if (prevLoggedIn == 0L) {
                    PrefUtils.getInstance().putLongPref(PrefKey.PREV_LOGGED_IN_USER_ID, currentUserId);
                } else if (!PrefUtils.getInstance().getLongPref(PrefKey.PREV_LOGGED_IN_USER_ID).equals(PrefUtils.getInstance().getLongPref(PrefKey.USER_ID))) {
                    mRepo.clearAllData(context);
                    PrefUtils.getInstance().putLongPref(PrefKey.PREV_LOGGED_IN_USER_ID, currentUserId);
                }
            }
        });

    }

    @Override
    public void clearPodcastStates() {
        mRepo.clearPodcastStates();
    }

    @Override
    public void getPodcastState(long podcastId, int position, DataSource.PodcastStateCallback callback) {
        mRepo.getPodcastState(podcastId, position, callback);
    }

    @Override
    public void checkNotifications() {
        mRepo.getUserSettings().subscribe(new CallbackWrapper<NotificationSettingsResponse>(mView) {
            @Override
            protected void onSuccess(NotificationSettingsResponse notificationSettingsResponse) {
                updateOneSignal(notificationSettingsResponse.getSettings());
            }

            @Override
            protected void onSuccessFalse(NotificationSettingsResponse notificationSettingsResponse) {
                updateOneSignal(new ArrayList<>());
            }
        });

    }

    @Override
    public void getSubscriptionList() {
        mRepo.getSubscription().subscribe(new CallbackWrapper<SubscriptionItemResponse>(mView) {
            @Override
            protected void onSuccess(SubscriptionItemResponse notificationSettingsResponse) {
                mView.subscriptionItem(notificationSettingsResponse);
            }

            @Override
            protected void onSuccessFalse(SubscriptionItemResponse notificationSettingsResponse) {
             //   updateOneSignal(new ArrayList<>());
            }
        });
    }

    @Override
    public void activatePaidSubscription(String subscription_plan, String planType, int duration,String purchaseToken) {
        mRepo.activePaidSubscription(subscription_plan,planType,duration,purchaseToken).subscribe(new CallbackWrapper<ActiveSubscriptionResponse>(mView) {
            @Override
            protected void onSuccess(ActiveSubscriptionResponse guestUserResponse) {
                if (mView != null) {
                    mView.onActivePaidSubscription(guestUserResponse);
                    mView.hideLoader();
                }
            }

            @Override
            protected void onSuccessFalse(ActiveSubscriptionResponse guestUserResponse) {
                if (mView != null) {
                    mView.hideLoader();
                }
            }
        });
    }

    private void updateOneSignal(List<NotificationSetting> settings) {
        // Set against what the user has previously set
        for (NotificationSetting setting :
                settings) {
            if (setting.getKey().equalsIgnoreCase("articles")) {
                OneSignal.deleteTag("writing");
                OneSignal.sendTag("writing", String.valueOf(setting.getValue()));
            } else {
                OneSignal.deleteTag(setting.getKey());
                OneSignal.sendTag(setting.getKey(), String.valueOf(setting.getValue()));
            }
        }

        // Set any remaining settings to 1
        OneSignal.getTags(tags -> {
            try {
                Log.d("checkNotifications tags", tags.toString());
                if (tags == null) {
                    tags = new JSONObject();
                }
                checkTag(tags, "podcasts");
                checkTag(tags, "videos");
                checkTag(tags, "bespoke");
                checkTag(tags, "writing");
                OneSignal.sendTags(tags);
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
                Log.d("checkNotifications", e.getMessage());
            }
        });
    }

    private void checkTag(JSONObject tags, String key) throws JSONException {
        if (!tags.has(key)) {
            tags.put(key, "1");
        }
    }
}
