/**
 * 
 */
package com.netflix.simianarmy.manic;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.netflix.simianarmy.MonkeyConfiguration;
import com.netflix.simianarmy.basic.chaos.BasicInstanceGroup;
import com.netflix.simianarmy.chaos.ChaosCrawler.InstanceGroup;
import com.netflix.simianarmy.client.gcloud.BasicChaosCrawler.Types;
import com.netflix.simianarmy.client.gcloud.BasicClient;

/**
 * @author dxiong
 *
 */
public class ManicGceClient extends BasicClient {

	private List<com.google.api.services.compute.model.Instance> cache = new ArrayList<com.google.api.services.compute.model.Instance>();
	private long cacheUpdatedAt = System.currentTimeMillis();

	private static final long CACHE_UPDATED_THTREDHOLD = 1 * 60 * 60 * 1000;// 1minute

	private synchronized void updateCache() throws IOException {
		updateCache(false);
	}
	
	private synchronized void updateCache(boolean force) throws IOException {
		if (force || cache.isEmpty() || (System.currentTimeMillis() - cacheUpdatedAt) >= CACHE_UPDATED_THTREDHOLD) {
			cache.clear();
			cache.addAll(internalList());
		}
	}

	private synchronized List<com.google.api.services.compute.model.Instance> getInstances() {
		List<com.google.api.services.compute.model.Instance> instances = new ArrayList<com.google.api.services.compute.model.Instance>();
		instances.addAll(cache);
		return instances;
	}

	/**
	 * @param configuration
	 * @throws Exception
	 */
	public ManicGceClient(MonkeyConfiguration configuration) throws Exception {
		super(configuration);
	}

	public List<InstanceGroup> listGroups() throws IOException {

		updateCache(true);

		List<InstanceGroup> groups = new ArrayList<InstanceGroup>();

		Set<String> tags = new HashSet<String>();

		for (com.google.api.services.compute.model.Instance instance : getInstances()) {
			tags.addAll(instance.getTags().getItems());
		}

		for (String tag : tags) {
			groups.add(new BasicInstanceGroup(tag, Types.TAG, zone, null));
		}

		return groups;

	}

	public List<Instance> list(String group) throws IOException {

		updateCache();

		List<Instance> instances = new ArrayList<Instance>();

		for (com.google.api.services.compute.model.Instance instance : getInstances()) {
			if (instance.getTags().getItems().contains(group)) {
				instances.add(new Instance(instance.getId().longValue(), instance.getName(),
						Status.parse(instance.getStatus())));
			}
		}

		return instances;
	}
}

@@ -172,16 +172,67 @@
 l.Set;%0A%0A
+import com.google.api.services.compute.model.Tags;%0A
 import c
@@ -974,17 +974,16 @@
 se);%0A%09%7D%0A
-%09
 %0A%09privat
@@ -1941,20 +1941,19 @@
 %0A%09%09%09
-tags.addAll(
+Tags tag = 
 inst
@@ -1958,32 +1958,99 @@
 stance.getTags()
+;%0A%09%09%09if (tag != null && tag.getItems() != null)%0A%09%09%09%09tags.addAll(tag
 .getItems());%0A%09%09

fix NullPointerException for a instance without tags