package net.ichigotake.common.os;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;

import java.io.Serializable;

public final class RestoreBundle {

    private final Bundle arguments;
    private final Bundle savedInstanceState;

    public RestoreBundle(Intent intent, Bundle savedInstanceState) {
        this((intent != null) ? intent.getExtras() : null, savedInstanceState);
    }

    public RestoreBundle(Fragment fragment, Bundle savedInstanceState) {
        this(fragment.getArguments(), savedInstanceState);
    }

    private RestoreBundle(Bundle arguments, Bundle savedInstanceState) {
        this.arguments = (arguments != null) ? arguments : new Bundle();
        this.savedInstanceState = (savedInstanceState != null) ? savedInstanceState : new Bundle();
    }

    public boolean containsKey(String key) {
        return arguments.containsKey(key) || savedInstanceState.containsKey(key);
    }

    public <T extends Parcelable> T getParcelable(String key) {
        T restoreObject;
        if (savedInstanceState.containsKey(key)) {
            restoreObject = savedInstanceState.getParcelable(key);
        } else if (arguments.containsKey(key)) {
            restoreObject = arguments.getParcelable(key);
        } else {
            restoreObject = null;
        }
        return restoreObject;
    }

    public <T extends Serializable> T getSerializable(String key) {
        T restoreObject;
        if (savedInstanceState.containsKey(key)) {
            restoreObject = (T)savedInstanceState.getSerializable(key);
        } else if (arguments.containsKey(key)) {
            restoreObject = (T)arguments.getSerializable(key);
        } else {
            restoreObject = null;
        }
        return restoreObject;
    }

}

@@ -1824,10 +1824,378 @@
 %0A    %7D%0A%0A
+    public int getInt(String key) %7B%0A        int restoreObject;%0A        if (savedInstanceState.containsKey(key)) %7B%0A            restoreObject = savedInstanceState.getInt(key);%0A        %7D else if (arguments.containsKey(key)) %7B%0A            restoreObject = arguments.getInt(key);%0A        %7D else %7B%0A            restoreObject = 0;%0A        %7D%0A        return restoreObject;%0A    %7D%0A
 %7D%0A

add RestoreBundle#getInt