package architect.commons.adapter;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import architect.StackScope;
import mortar.MortarScope;
import architect.StackPath;
import architect.StackFactory;

/**
 * @author Lukasz Piliszczuk - lukasz.pili@gmail.com
 */
public class StackPagerAdapter extends PagerAdapter {

    private final Context context;
    private final List<StackPath> paths;
    private final Map<StackPath, StackScope> scopes;

    public StackPagerAdapter(Context context, StackPath... paths) {
        this.context = context;
        this.paths = Arrays.asList(paths);
        scopes = new HashMap<>();
    }

    @Override
    public int getCount() {
        return paths.size();
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        StackPath path = paths.get(position);
        StackScope scope = scopes.get(path);
        if (scope == null) {
            scope = path.createScope();
            scopes.put(path, scope);
        }

        Context pageContext = StackFactory.createContext(context, scope, String.valueOf(position));
        View newChild = path.createView(pageContext);
        container.addView(newChild);
        return newChild;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        View view = ((View) object);
        MortarScope scope = MortarScope.getScope(view.getContext());
        container.removeView(view);
        scope.destroy();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view.equals(object);
    }
}

@@ -106,16 +106,49 @@
 dapter;%0A
+import android.util.SparseArray;%0A
 import a
@@ -243,117 +243,44 @@
 til.
-HashMap;%0Aimport java.util.List;%0Aimport java.util.Map;%0A%0Aimport architect.StackScope;%0Aimport mortar.MortarScope
+List;%0A%0Aimport architect.StackFactory
 ;%0Aim
@@ -327,23 +327,48 @@
 ct.Stack
-Factory
+Scope;%0Aimport mortar.MortarScope
 ;%0A%0A/**%0A 
@@ -576,23 +576,20 @@
 nal 
-Map%3CStackPath, 
+SparseArray%3C
 Stac
@@ -669,24 +669,147 @@
 .. paths) %7B%0A
+        this(context, Arrays.asList(paths));%0A    %7D%0A%0A    public StackPagerAdapter(Context context, List%3CStackPath%3E paths) %7B%0A
         this
@@ -849,36 +849,21 @@
 paths = 
-Arrays.asList(
 paths
-)
 ;%0A      
@@ -881,18 +881,34 @@
 new 
-HashMap%3C%3E(
+SparseArray%3C%3E(paths.size()
 );%0A 
@@ -1161,19 +1161,23 @@
 es.get(p
-ath
+osition
 );%0A     
@@ -1264,19 +1264,23 @@
 es.put(p
-ath
+osition
 , scope)
@@ -1772,24 +1772,57 @@
 .destroy();%0A
+        scopes.remove(position);%0A
     %7D%0A%0A    @

Improve StackPagerAdapter.