package com.hikapro.backpack;

import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.util.Log;

import java.lang.ref.WeakReference;
import java.util.HashMap;

/**
 * Created by tariel on 24/04/16.
 */
public class StateMaintainer {

    private final String stateMaintainerTag;
    private final WeakReference<FragmentManager> fragmentManager;
    private StateMngFragment stateMngFragment;
    private boolean isRecreating;


    public StateMaintainer(FragmentManager fragmentManager, String stateMaintainerTAG) {
        this.fragmentManager = new WeakReference<>(fragmentManager);
        this.stateMaintainerTag = stateMaintainerTAG;
    }

    public boolean init() {
        try {
            stateMngFragment = (StateMngFragment)
                    fragmentManager.get().findFragmentByTag(stateMaintainerTag);

            if (stateMngFragment == null) {
                stateMngFragment = new StateMngFragment();
                fragmentManager.get().beginTransaction()
                        .add(stateMngFragment, stateMaintainerTag).commit();
                isRecreating = false;
                return true;
            } else {
                isRecreating = true;
                return false;
            }
        } catch (NullPointerException e) {
            return false;
        }
    }

    public boolean wasRecreated() { return isRecreating; }

    public void put(String key, Object obj) {
        stateMngFragment.put(key, obj);
    }

    public void put(Object obj) {
        put(obj.getClass().getName(), obj);
    }

    public <T> T get(String key)  {
        return stateMngFragment.get(key);

    }

    public boolean hasKey(String key) {
        return stateMngFragment.get(key) != null;
    }


    public static class StateMngFragment extends Fragment {

        private HashMap<String, Object> data = new HashMap<>();

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setRetainInstance(true);
        }


        public void put(String key, Object obj) {
            data.put(key, obj);
        }


        public void put(Object object) {
            put(object.getClass().getName(), object);
        }


        @SuppressWarnings("unchecked")
        public <T> T get(String key) {
            return (T) data.get(key);
        }
    }
}
