/*
 * Copyright (c) 2002-2011 JSCAPE
 * 1147 S. 53rd Pl., Mesa, Arizona, 85206, U.S.A.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * JSCAPE. ("Confidential Information").  You shall not disclose such
 * Confidential Information and shall use it only in accordance with
 *  the terms of the license agreement you entered into with JSCAPE.
 */

package com.jscape.util;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

import static com.jscape.util.Parameters.assertNotNull;

/**
 * @author Alex Usun
 */
public class NamedThreadFactory
        implements ThreadFactory {

    protected final String nameTemplate;
    protected final ThreadType type;
    protected final AtomicInteger count;

    public static ThreadFactory daemonsFactory(String template) {
        return new NamedThreadFactory(template, ThreadType.DAEMON);
    }

    public static ThreadFactory usersFactory(String template) {
        return new NamedThreadFactory(template, ThreadType.USER);
    }

    public NamedThreadFactory(String nameTemplate, ThreadType type) {
        assertNotNull(nameTemplate);
        this.nameTemplate = nameTemplate;

        this.count = new AtomicInteger(0);

        assertNotNull(type);
        this.type = type;
    }

    public Thread newThread(Runnable target) {
        String name = String.format(this.nameTemplate, this.count.incrementAndGet());
        Thread thread = threadFor(name, target);
        this.type.setup(thread);

        return thread;
    }

    protected Thread threadFor(String name, Runnable target) {
        return new Thread(target, name);
    }

    public enum ThreadType {

        USER() {
            public void setup(Thread thread) {
                thread.setDaemon(false);
            }
        },

        DAEMON() {
            public void setup(Thread thread) {
                thread.setDaemon(true);
            }
        };

        public abstract void setup(Thread thread);

    }
}
