/*
 * Copyright 2013 Rackspace
 *
 *    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 com.rackspacecloud.blueflood.concurrent;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.Gauge;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;

public class ThreadPoolBuilder {
    private static final Logger log = LoggerFactory.getLogger(ThreadPoolBuilder.class);

    private int corePoolSize = 10;
    private int maxPoolSize = 10;
    private int queueSize = 0;
    
    private RejectedExecutionHandler rejectedHandler = new ThreadPoolExecutor.CallerRunsPolicy();
    private Thread.UncaughtExceptionHandler exceptionHandler = new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            log.error(e.getMessage(), e);
        }
    };
    private String name = "Thread";

    public ThreadPoolBuilder() {

    }

    public ThreadPoolBuilder withCorePoolSize(int size) {
        this.corePoolSize = size;
        return this;
    }

    public ThreadPoolBuilder withMaxPoolSize(int size) {
        this.maxPoolSize = size;
        return this;
    }

    public ThreadPoolBuilder withUnboundedQueue() {
        this.queueSize = 0;
        return this;
    }

    public ThreadPoolBuilder withBoundedQueue(int size) {
        this.queueSize = size;
        return this;
    }

    public ThreadPoolBuilder withRejectedHandler(RejectedExecutionHandler rejectedHandler) {
        this.rejectedHandler = rejectedHandler;
        return this;
    }

    public ThreadPoolBuilder withName(String name) {
        // ensure we've got a spot to put the thread id.
        if (name.indexOf("%d") < 0) {
            name = name + "-%d";
        }
        this.name = name;
        return this;

    }

    public ThreadPoolBuilder withExeptionHandler(Thread.UncaughtExceptionHandler exceptionHandler) {
        this.exceptionHandler = exceptionHandler;
        return this;
    }

    public ThreadPoolExecutor build() {
        String metricName = name.subSequence(0, name.length() - 3) + " work queue size"; // don't need the '-%d'
        final BlockingQueue<Runnable> workQueue = this.queueSize > 0 ? new ArrayBlockingQueue<Runnable>(queueSize) :
                    new LinkedBlockingQueue<Runnable>();
        
        // todo: needs to be included as a member in the ThreadPoolExecutor.
        Gauge<Integer> workQueueSize = Metrics.newGauge(ThreadPoolBuilder.class, metricName, new Gauge<Integer>() {
            @Override
            public Integer value() {
                return workQueue.size();
            }
        });
        
        return new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                30, TimeUnit.SECONDS, // hard code the timeout.
                workQueue,
                new ThreadFactoryBuilder().setNameFormat(name).setPriority(Thread.NORM_PRIORITY).setUncaughtExceptionHandler(exceptionHandler).build(),
                rejectedHandler);
    }
}
@@ -2736,22 +2736,16 @@
         
-final 
 Blocking
@@ -2917,57 +2917,31 @@
     
-// todo: needs to be included as a member in the 
+return new Instrumented
 Thre
@@ -2954,17 +2954,17 @@
 Executor
-.
+(
 %0A       
@@ -2968,197 +2968,489 @@
     
-Gauge%3CInteger%3E workQueueSize = Metrics.newGauge(ThreadPoolBuilder.class, metricName, new Gauge%3CInteger%3E() %7B%0A            @Override
+        metricName,%0A                corePoolSize,%0A                maxPoolSize,%0A                30, TimeUnit.SECONDS, // hard code the timeout.%0A                workQueue,%0A                new ThreadFactoryBuilder().setNameFormat(name).setPriority(Thread.NORM_PRIORITY).setUncaughtExceptionHandler(exceptionHandler).build(),%0A                rejectedHandler);
 %0A    
+%7D%0A
     
+%0A
     p
-ublic Integer value() %7B%0A                return
+rivate class InstrumentedThreadPoolExecutor extends ThreadPoolExecutor %7B%0A        private final Gauge%3CInteger%3E
  wor
@@ -3459,15 +3459,12 @@
 ueue
-.s
+S
 ize
-()
 ;%0A  
@@ -3465,29 +3465,24 @@
 ze;%0A        
-    %7D
 %0A        %7D);
@@ -3482,40 +3482,27 @@
     
-%7D);%0A        %0A        return new 
+public Instrumented
 Thre
@@ -3508,32 +3508,44 @@
 eadPoolExecutor(
+String name,
 %0A               
@@ -3549,41 +3549,113 @@
     
-corePoolSize,%0A                max
+                              int corePoolSize,%0A                                              int maximum
 Pool
@@ -3680,268 +3680,741 @@
     
+        
-30, TimeUnit.SECONDS, // hard code the timeout.%0A                workQueue,%0A                new ThreadFactoryBuilder().setNameFormat(name).setPriority(Thread.NORM_PRIORITY).setUncaughtExceptionHandler(exceptionHandler).build(),%0A                rejectedHandler);
+                      long keepAliveTime,%0A                                              TimeUnit unit,%0A                                              final BlockingQueue%3CRunnable%3E workQueue,%0A                                              ThreadFactory threadFactory,%0A                                              RejectedExecutionHandler handler) %7B%0A            super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);%0A            %0A            this.workQueueSize = Metrics.newGauge(ThreadPoolBuilder.class, name, new Gauge%3CInteger%3E() %7B%0A                @Override%0A                public Integer value() %7B%0A                    return workQueue.size();%0A                %7D%0A            %7D);%0A        %7D
 %0A   

create a subclass that wraps a guage that tracks worker queue size.