package ml.docilealligator.infinityforreddit.post;

import android.content.SharedPreferences;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.paging.ListenableFuturePagingSource;
import androidx.paging.PagingState;

import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;

import ml.docilealligator.infinityforreddit.RedditDataRoomDatabase;
import ml.docilealligator.infinityforreddit.RedditError;
import ml.docilealligator.infinityforreddit.account.Account;
import ml.docilealligator.infinityforreddit.apis.RedditAPI;
import ml.docilealligator.infinityforreddit.postfilter.PostFilter;
import ml.docilealligator.infinityforreddit.readpost.NullReadPostsList;
import ml.docilealligator.infinityforreddit.readpost.ReadPost;
import ml.docilealligator.infinityforreddit.readpost.ReadPostType;
import ml.docilealligator.infinityforreddit.utils.APIUtils;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.HttpException;
import retrofit2.Response;
import retrofit2.Retrofit;

public class HistoryPostPagingSource extends ListenableFuturePagingSource<String, Post> {
    private final Retrofit retrofit;
    private final Executor executor;
    private final RedditDataRoomDatabase redditDataRoomDatabase;
    private final String accessToken;
    private final String accountName;
    private final SharedPreferences sharedPreferences;
    private final String username;
    private final int readPostType;
    private final PostFilter postFilter;

    public HistoryPostPagingSource(Retrofit retrofit, Executor executor, RedditDataRoomDatabase redditDataRoomDatabase,
                                   @Nullable String accessToken, @NonNull String accountName, SharedPreferences sharedPreferences,
                                   String username, int readPostType, PostFilter postFilter) {
        this.retrofit = retrofit;
        this.executor = executor;
        this.redditDataRoomDatabase = redditDataRoomDatabase;
        this.accessToken = accessToken;
        this.accountName = accountName;
        this.sharedPreferences = sharedPreferences;
        this.username = username;
        this.readPostType = readPostType;
        this.postFilter = postFilter;
    }

    @Nullable
    @Override
    public String getRefreshKey(@NonNull PagingState<String, Post> pagingState) {
        return null;
    }

    @NonNull
    @Override
    public ListenableFuture<LoadResult<String, Post>> loadFuture(@NonNull LoadParams<String> loadParams) {
        return loadReadPosts(loadParams, redditDataRoomDatabase);
    }

    public LoadResult<String, Post> transformData(List<ReadPost> readPosts) {
        StringBuilder ids = new StringBuilder();
        long lastItem = 0;
        for (ReadPost readPost : readPosts) {
            ids.append("t3_").append(readPost.getId()).append(",");
            lastItem = readPost.getTime();
        }
        if (ids.length() > 0) {
            ids.deleteCharAt(ids.length() - 1);
        }

        Call<String> historyPosts;
        if (accountName.equals(Account.ANONYMOUS_ACCOUNT)) {
            historyPosts = retrofit.create(RedditAPI.class).getInfo(ids.toString());
        } else {
            historyPosts = retrofit.create(RedditAPI.class).getInfoOauth(ids.toString(), APIUtils.getOAuthHeader(accessToken));
        }

        try {
            Response<String> response = historyPosts.execute();
            if (response.isSuccessful()) {
                String responseString = response.body();
                LinkedHashSet<Post> newPosts = ParsePost.parsePostsSync(responseString, -1, postFilter, NullReadPostsList.getInstance());
                if (newPosts == null) {
                    return new LoadResult.Error<>(new PostPagingSource.PostPagingSourceError(response.code(), "Error parsing posts"));
                } else {
                    if (accountName.equals(Account.ANONYMOUS_ACCOUNT)) {
                        setMetadataToAnonymousPosts(newPosts);
                    }

                    if (newPosts.size() < 25) {
                        return new LoadResult.Page<>(new ArrayList<>(newPosts), null, null);
                    }
                    return new LoadResult.Page<>(new ArrayList<>(newPosts), null, Long.toString(lastItem));
                }
            } else {
                try (ResponseBody errorBody = response.errorBody()) {
                    if (errorBody != null) {
                        RedditError redditError = new Gson().fromJson(errorBody.string(), RedditError.class);
                        return new LoadResult.Error<>(new PostPagingSource.PostPagingSourceError(response.code(), redditError.getReason()));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return new LoadResult.Error<>(new PostPagingSource.PostPagingSourceError(response.code(), null));
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new LoadResult.Error<>(new PostPagingSource.PostPagingSourceError(0, "Error getting response"));
        }
    }

    private void setMetadataToAnonymousPosts(LinkedHashSet<Post> posts) {
        for (Post p : posts) {
            switch (readPostType) {
                case ReadPostType.ANONYMOUS_UPVOTED_POSTS:
                    p.setVoteType(1);
                    break;
                case ReadPostType.ANONYMOUS_DOWNVOTED_POSTS:
                    p.setVoteType(-1);
                    break;
                case ReadPostType.ANONYMOUS_HIDDEN_POSTS:
                    p.setHidden(true);
                    break;
                case ReadPostType.ANONYMOUS_SAVED_POSTS:
                    p.setSaved(true);
                    break;
            }
        }

        List<ReadPost> readPostsInDatabase = redditDataRoomDatabase.readPostDao().getAllReadPostsForMetadata(
                accountName, readPostType, posts.stream().map(Post::getId).collect(Collectors.toList()));
        Map<String, Post> existingPostsMap = posts.stream().collect(Collectors.toMap(Post::getId, post -> post));
        for (ReadPost r : readPostsInDatabase) {
            Post existingPost = existingPostsMap.get(r.getId());
            if (existingPost != null) {
                switch (r.getReadPostType()) {
                    case ReadPostType.ANONYMOUS_UPVOTED_POSTS:
                        existingPost.setVoteType(1);
                        break;
                    case ReadPostType.ANONYMOUS_DOWNVOTED_POSTS:
                        existingPost.setVoteType(-1);
                        break;
                    case ReadPostType.ANONYMOUS_HIDDEN_POSTS:
                        existingPost.setHidden(true);
                        break;
                    case ReadPostType.ANONYMOUS_SAVED_POSTS:
                        existingPost.setSaved(true);
                        break;
                }
            }
        }
    }

    private ListenableFuture<LoadResult<String, Post>> loadReadPosts(@NonNull LoadParams<String> loadParams, RedditDataRoomDatabase redditDataRoomDatabase) {
        Long before = loadParams.getKey() != null ? Long.parseLong(loadParams.getKey()) : null;
        ListenableFuture<List<ReadPost>> readPosts = redditDataRoomDatabase.readPostDao().getAllReadPostsListenableFuture(username, before, readPostType);

        ListenableFuture<LoadResult<String, Post>> pageFuture = Futures.transform(readPosts, this::transformData, executor);

        ListenableFuture<LoadResult<String, Post>> partialLoadResultFuture =
                Futures.catching(pageFuture, HttpException.class,
                        LoadResult.Error::new, executor);

        return Futures.catching(partialLoadResultFuture,
                IOException.class, LoadResult.Error::new, executor);
    }
}
