package com.trevore.rodrigo.rx;

import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Observable provider with a cache mechanism. If you don't need to cache the observable, create it directly.
 * Created by rtang on 15/10/15.
 */
public class CachedObservableProvider<T> {
    public static final String TAG = "com.kayak.android.common.net.CachedObservableProvider";
    private static final long SEARCH_TIMEOUT = TimeUnit.MINUTES.toMillis(20);

    private final FragmentManager mFragmentManager;

    public CachedObservableProvider(@NonNull FragmentManager fragmentManager) {
        mFragmentManager = fragmentManager;
    }

    /**
     * Try to get cached Observable, if it doesn't exist, create a new one and put it into cache system.
     */
    @NonNull
    public Observable<T> getObservable(RxCacheProvider<T> cacheProvider) {
        String cacheKey = cacheProvider.createCacheKey();
        Observable<T> observable;
        CacheFragment cacheFragment;
        cacheFragment = getCacheFragment(mFragmentManager);

        observable = cacheFragment.getObservable(cacheKey);
        if (observable == null) {
            observable = cacheProvider.createOriginalObservable();
            observable = observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());

            observable = observable.cache();
            cacheFragment.putObservable(cacheKey, observable);
        } else {
            observable = cacheProvider.transformCache(observable);
        }

        return observable;
    }

    private CacheFragment getCacheFragment(FragmentManager fragmentManager) {
        Fragment fragment = fragmentManager.findFragmentByTag(TAG);
        CacheFragment cacheFragment;
        if (fragment == null) {
            cacheFragment = new CacheFragment();
            fragmentManager.beginTransaction().add(cacheFragment, TAG).commit();
        } else {
            cacheFragment = (CacheFragment) fragment;
        }
        cacheFragment.setCacheLifeTime(SEARCH_TIMEOUT);
        return cacheFragment;
    }
}

@@ -1234,27 +1234,11 @@
 ent(
-mFragmentManager
 );%0A
+
 %0A   
@@ -1788,39 +1788,8 @@
 ent(
-FragmentManager fragmentManager
 ) %7B%0A
@@ -1816,17 +1816,18 @@
 gment = 
-f
+mF
 ragmentM
@@ -1987,17 +1987,18 @@
         
-f
+mF
 ragmentM
@@ -2224,16 +2224,297 @@
 agment;%0A
-
     %7D%0A
+%0A    public void clearAllCache() %7B%0A        CacheFragment cacheFragment = getCacheFragment();%0A        cacheFragment.clearCache();%0A    %7D%0A%0A    public void clearCache(String key) %7B%0A        CacheFragment cacheFragment = getCacheFragment();%0A        cacheFragment.clearCache(key);%0A    %7D%0A%0A
 %7D%0A

support clear cache