/*
 * Copyright 2009-2017 Aconex
 *
 * Licensed 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.
 */

package io.pcp.parfait;

import static org.junit.Assert.assertEquals;
import static tec.uom.se.AbstractUnit.ONE;

import org.junit.Test;

import com.google.common.base.Supplier;

public class PollingMonitoredValueTest {

	@Test
	public void shouldScheduleTaskAtDesiredRate() {
		TestPoller poller = new TestPoller();
		ManualScheduler scheduler = new ManualScheduler();
		new PollingMonitoredValue<Integer>("polling.test", "",
				new MonitorableRegistry(), 275, poller,
				ValueSemantics.FREE_RUNNING, ONE, scheduler);
		assertEquals(1, scheduler.scheduledRates.size());
		assertEquals(275, scheduler.scheduledRates.values().iterator().next()
				.intValue());
	}

	@Test
	public void scheduledTaskExecutionShouldUpdateValue()
			throws InterruptedException {
		TestPoller poller = new TestPoller();
		MonitorableRegistry registry = new MonitorableRegistry();
		ManualScheduler scheduler = new ManualScheduler();
		PollingMonitoredValue<Integer> p = new PollingMonitoredValue<Integer>(
				"polling.test", "", registry, 275,
				poller, ValueSemantics.FREE_RUNNING, ONE, scheduler);
		poller.value = 17;
		assertEquals(0, p.get().intValue());
		scheduler.runAllScheduledTasks();
		assertEquals(17, p.get().intValue());
	}

	private final class TestPoller implements Supplier<Integer> {
		private int value = 0;

		public Integer get() {
			return value;
		}
	}

}
