/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * $Header:$
 */

import java.util.Iterator;

import org.apache.beehive.controls.api.bean.Control;
import org.apache.beehive.controls.api.context.ControlContainerContext;
import org.apache.beehive.controls.api.context.ControlThreadContext;
import org.apache.beehive.netui.pageflow.Forward;
import org.apache.beehive.netui.pageflow.PageFlowController;
import org.apache.beehive.netui.pageflow.annotations.Jpf;

import controls.OuterControl;

import service.EventRecorderServiceProvider;
import service.EventRecorderService;

/**
 * Demonstrates controls life cycle and resource events and the use of a
 * custom service provider for Beehive controls.
 */
@Jpf.Controller(forwards = {@Jpf.Forward(name="index", path="index.jsp")})
public class Controller extends PageFlowController {
	private static final long serialVersionUID = -125820123L;

	private EventRecorderServiceProvider _lfService;
	
	@Control
	private OuterControl _ctrl;
	
	/**
	 * Callback that is invoked when this controller instance is created.
     * Registers the custom service provider with the ControlContainerContext.
	 */
	@Override
	protected void onCreate() {
		ControlContainerContext ccc = ControlThreadContext.getContext();
		_lfService = new EventRecorderServiceProvider();
		ccc.addService(EventRecorderService.class, _lfService);
	}

	@Jpf.Action
	protected Forward begin() {
		return new Forward("index");
	}

    /**
     * Invoke a method on _ctrl, does not cause any nested control
     * methods to be invoked.
     */
    @Jpf.Action
	protected Forward invokeOuterControlMethod() {
		_ctrl.outerMethod();
		return new Forward("index");
	}

    /**
     * Invoked a method on _ctrl, which in turn invokes methods on
     * an inner control.
     */
    @Jpf.Action
	protected Forward invokeInnerControlMethod() {
		_ctrl.invokeInnerControlMethod();
		return new Forward("index");
	}

    /**
     * Get an Iterator for all logged events from the event recorder service.
     */
    public Iterator<String> getControlEvents() {
		EventRecorderService lr = (EventRecorderService)_lfService.getService(null, null, EventRecorderService.class, null);
		return lr.getEvents();
	}
}