package com.stardust.util;

import android.content.Intent;
import android.util.SparseArray;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Stardust on 2017/7/11.
 */

public class IntentExtras implements Serializable {

    private static int mMaxId = -1;
    private static final String EXTRA_ID = "com.stardust.util.IntentExtras.id";
    private static SparseArray<Map<String, Object>> extraStore = new SparseArray<>();


    public static IntentExtras newExtras() {
        return new IntentExtras();
    }

    public static IntentExtras fromIntent(Intent intent) {
        int id = intent.getIntExtra(EXTRA_ID, -1);
        if (id < 0) {
            throw new IllegalArgumentException("");
        }
        return new IntentExtras(id);
    }

    private Map<String, Object> mMap;
    private int mId;

    private IntentExtras() {
        mMap = new HashMap<>();
        mMaxId++;
        mId = mMaxId;
        extraStore.put(mId, mMap);
    }


    private IntentExtras(int id) {
        mMap = extraStore.get(id);
        extraStore.remove(id);
        mMaxId = id;
    }


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

    @SuppressWarnings("unchecked")
    public <T> T getAndClear(String key) {
        T value = (T) mMap.get(key);
        recycle();
        return value;
    }

    public IntentExtras put(String key, Object value) {
        mMap.put(key, value);
        return this;
    }

    public Intent putInIntent(Intent intent) {
        intent.putExtra(EXTRA_ID, mMaxId);
        return intent;
    }

    public void recycle() {
        extraStore.remove(mId);
        mMap = null;
    }
}

@@ -162,16 +162,66 @@
 til.Map;
+%0Aimport java.util.concurrent.atomic.AtomicInteger;
 %0A%0A/**%0A *
@@ -336,23 +336,52 @@
 tic 
-int mMaxId = 
+AtomicInteger mMaxId = new AtomicInteger(
 -1
+)
 ;%0A  
@@ -816,10 +816,8 @@
 ion(
-%22%22
 );%0A 
@@ -910,29 +910,8 @@
 Map;
-%0A    private int mId;
 %0A%0A  
@@ -981,38 +981,41 @@
     
-mMaxId++;%0A        mId = mMaxId
+int id = mMaxId.incrementAndGet()
 ;%0A  
@@ -1035,18 +1035,17 @@
 ore.put(
-mI
+i
 d, mMap)
@@ -1120,24 +1120,98 @@
 re.get(id);%0A
+        if (mMap == null) %7B%0A            mMap = new HashMap%3C%3E();%0A        %7D%0A
         extr
@@ -1233,29 +1233,8 @@
 d);%0A
-        mMaxId = id;%0A
     
@@ -1352,171 +1352,8 @@
  %7D%0A%0A
-    @SuppressWarnings(%22unchecked%22)%0A    public %3CT%3E T getAndClear(String key) %7B%0A        T value = (T) mMap.get(key);%0A        recycle();%0A        return value;%0A    %7D%0A%0A
     
@@ -1548,24 +1548,24 @@
 D, mMaxId);%0A
+
         retu
@@ -1584,95 +1584,7 @@
    %7D
-%0A%0A    public void recycle() %7B%0A        extraStore.remove(mId);%0A        mMap = null;%0A    %7D
 %0A%7D%0A

fix hyb1996-guest/auto.js3-issues#5