/*
 * Copyright 2004-2014 the Seasar Foundation and the Others.
 *
 * 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 org.seasar.extension.timer;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

/**
 * @author higa
 *
 */
public class TimeoutManagerTest {

    /** TimeoutManager */
    private TimeoutManager tm = null;

    /**
     * setUp
     */
    @Before
    public void setUp() {
        this.tm = TimeoutManager.getInstance();
        this.tm.clear();
    }

    /**
     * tearDown
     */
    @AfterClass
    public static void tearDown() {
        TimeoutManager.getInstance().clear();
    }

    /**
     * testExpired
     * @throws Exception Exception
     */
    @Test
    public void testExpired() throws Exception {
        final Target tt = new Target();
        final TimeoutTask task = this.tm.addTimeoutTarget(tt, 1, true);

        Assert.assertNotNull(this.tm.getThread());
        Thread.sleep(2000);
        Assert.assertTrue(tt.getExpiredCount() > 0);
        Assert.assertEquals(1, this.tm.getTimeoutTaskCount());
        this.tm.stop();

        Assert.assertNull(this.tm.getThread());
        Thread.sleep(10);
        final int count = tt.getExpiredCount();
        task.stop();
        System.out.println(count);

        this.tm.start();
        Assert.assertNotNull(this.tm.getThread());
        Thread.sleep(2000);
        Assert.assertEquals(count, tt.getExpiredCount());
        Assert.assertEquals(1, this.tm.getTimeoutTaskCount());
        task.cancel();
        Thread.sleep(2000);
        Assert.assertEquals(0, this.tm.getTimeoutTaskCount());
        Assert.assertNull(this.tm.getThread());
    }

    /**
     * TimeoutTarget
     *
     */
    static final class Target implements TimeoutTarget {
        /** expiredCount */
        private int expiredCount = 0;

        /**
         * get expiredCount
         * @return expiredCount
         */
        public int getExpiredCount() {
            return this.expiredCount;
        }

        /**
         * @see org.seasar.extension.timer.TimeoutTarget#expired()
         */
        @Override
        public void expired() {
            System.out.println("expired");
            this.expiredCount++;
        }
    }
}
