// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc.component;

import com.yahoo.component.AbstractComponent;
import com.yahoo.concurrent.ThreadFactoryFactory;
import com.yahoo.container.di.ComponentDeconstructor;
import com.yahoo.container.di.componentgraph.Provider;
import com.yahoo.jdisc.SharedResource;

import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

import static java.util.logging.Level.WARNING;

/**
* @author tonyv
* @author gv
*/
public class Deconstructor implements ComponentDeconstructor {
    private static final Logger log = Logger.getLogger(Deconstructor.class.getName());

    private final ScheduledExecutorService executor =
            Executors.newScheduledThreadPool(1, ThreadFactoryFactory.getDaemonThreadFactory("deconstructor"));

    private final int delay;

    public Deconstructor(boolean delayDeconstruction) {
        delay = delayDeconstruction ? 60 : 0;
    }


    @Override
    public void deconstruct(Object component) {
        if (component instanceof AbstractComponent) {
            AbstractComponent abstractComponent = (AbstractComponent) component;
            if (abstractComponent.isDeconstructable()) {
                log.info("Scheduling deconstruction of " + abstractComponent);
                executor.schedule(new DestructComponentTask(abstractComponent), delay, TimeUnit.SECONDS);
            }
        } else if (component instanceof Provider) {
            ((Provider)component).deconstruct();
        } else if (component instanceof SharedResource) {
            // No need to delay release, as jdisc does ref-counting
            ((SharedResource)component).release();
        }
    }

    private static class DestructComponentTask implements Runnable {
        private final AbstractComponent component;

        DestructComponentTask(AbstractComponent component) {
            this.component = component;
        }

        public void run() {
            log.info("Starting deconstruction of " + component);
            try {
                component.deconstruct();
                log.info("Finished deconstructing " + component);
            } catch (Error e) {
                try {
                    Thread.sleep((long) (new Random(System.nanoTime()).nextDouble() * 180 * 1000));
                } catch (InterruptedException e) { }
                com.yahoo.protect.Process.logAndDie("Error when deconstructing " + component, e);
            } catch (Exception e) {
                log.log(WARNING, "Exception thrown when deconstructing " + component, e);
            } catch (Throwable t) {
                log.log(WARNING, "Unexpected Throwable thrown when deconstructing " + component, t);
            }
        }
    }
}

@@ -402,33 +402,8 @@
 e;%0A%0A
-import java.util.Random;%0A
 impo
@@ -567,56 +567,8 @@
 r;%0A%0A
-import static java.util.logging.Level.WARNING;%0A%0A
 /**%0A
@@ -2130,38 +2130,16 @@
 onent);%0A
-            try %7B%0A    
         
@@ -2163,28 +2163,24 @@
 onstruct();%0A
-    
             
@@ -2233,590 +2233,8 @@
 t);%0A
-            %7D catch (Error e) %7B%0A                try %7B%0A                    Thread.sleep((long) (new Random(System.nanoTime()).nextDouble() * 180 * 1000));%0A                %7D catch (InterruptedException e) %7B %7D%0A                com.yahoo.protect.Process.logAndDie(%22Error when deconstructing %22 + component, e);%0A            %7D catch (Exception e) %7B%0A                log.log(WARNING, %22Exception thrown when deconstructing %22 + component, e);%0A            %7D catch (Throwable t) %7B%0A                log.log(WARNING, %22Unexpected Throwable thrown when deconstructing %22 + component, t);%0A            %7D%0A
     

Revert "Revert "Revert "Catch exception thrown from AbstractComponent.deconstruct."""