package org.jerrymouse.cc.site.view;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import org.jerrymouse.cc.site.bean.Resource;
import org.jerrymouse.cc.site.bean.Type;
import org.jerrymouse.cc.site.bean.User;
import org.jerrymouse.cc.site.view.display.DefaultDisplayer;
import org.jerrymouse.cc.site.view.display.Displayer;
import org.jerrymouse.cc.site.view.display.HTML5VideoDisplayer;
import org.jerrymouse.cc.site.view.redirecter.GoogleDocRedirect;
import org.jerrymouse.cc.site.view.redirecter.Redirecter;
import org.jerrymouse.cc.site.view.redirecter.ZohoRedirecter;

public class CommonViewer {

	private static List<Viewer> viewers;

	static {
		viewers = new ArrayList<Viewer>();
		viewers.add(new HTML5VideoDisplayer());
		viewers.add(new GoogleDocRedirect());
		viewers.add(new ZohoRedirecter());
	}

	public ResponseBuilder view(Resource resource) {
		Viewer viewer = bestFitViewer(resource.getUser(), resource.getOrgType());
		if (viewer instanceof Redirecter) {
			return Response.seeOther(((Redirecter) viewer).view(resource));
		} else if (viewer instanceof Displayer) {
			return ((Displayer) viewer).display(resource).createResponse();
		}
		return null;
	}

	private Viewer bestFitViewer(User user, Type type) {
		for (Viewer v : viewers) {
			if (v.support().contains(type)) {
				return v;
			}
		}
		return new DefaultDisplayer();
	}

}
