package com.sinyuk.yuk.data.shot;

import android.support.annotation.NonNull;

import com.f2prateek.rx.preferences.RxSharedPreferences;
import com.sinyuk.yuk.api.DribbleService;

import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import timber.log.Timber;

/**
 * Created by Sinyuk on 16.6.20.
 */
public class ShotRepository {
    private final HashMap<String, LinkedList<Shot>> mShotCache = new HashMap<>();
    private final RxSharedPreferences prefs;
    DribbleService mDribbleService;

    public ShotRepository(DribbleService dribbleService,
                          RxSharedPreferences preferences) {
        this.mDribbleService = dribbleService;
        this.prefs = preferences;
        Timber.tag("ShotRepository");
    }

    public Observable<List<Shot>> getShots(@NonNull String type, int page) {
        Observable<List<Shot>> cachingObservable = mDribbleService.shots(type, page);
        return cachingObservable
                .map(insertShots(page, type))
                .subscribeOn(Schedulers.io())
                .doOnError(throwable -> mShotCache.remove(type))
                .observeOn(AndroidSchedulers.mainThread());
    }

    private Func1<List<Shot>, List<Shot>> insertShots(int page, String type) {
        return result -> {
            LinkedList<Shot> list = mShotCache.get(type);
            if (list == null) {
                list = new LinkedList<>();
            }
            if (page == 1) {
                if (Collections.disjoint(list, result)) {
                    list.clear();
                    list.addAll(result);
                } else {
                    result.removeAll(list);
                    list.addAll(0, result);
                }
            } else {
                list.addAll(result);    // append to front
            }
            mShotCache.put(type, list);
            return list;
        };
    }
}

@@ -176,38 +176,8 @@
 e;%0A%0A
-import java.util.Collections;%0A
 impo
@@ -1585,24 +1585,61 @@
 age == 1) %7B%0A
+                //%E4%B8%8D%E4%BF%9D%E5%AD%98%E6%97%A7%E6%95%B0%E6%8D%AE%E4%BA%86 %E5%8F%AA%E8%A6%81%E5%88%B7%E6%96%B0%E5%85%A8%E9%83%A8%E6%B8%85%E9%99%A4%0A//
             
@@ -1680,24 +1680,26 @@
  result)) %7B%0A
+//
             
@@ -1716,24 +1716,26 @@
 st.clear();%0A
+//
             
@@ -1755,32 +1755,34 @@
 addAll(result);%0A
+//
                 
@@ -1782,32 +1782,34 @@
        %7D else %7B%0A
+//
                 
@@ -1832,24 +1832,26 @@
 eAll(list);%0A
+//
             
@@ -1878,24 +1878,26 @@
 0, result);%0A
+//
             
@@ -1894,32 +1894,99 @@
               %7D%0A
+                list.clear();%0A                list.addAll(result);%0A
             %7D el

Clear list when refresh