/*
 * Copyright (C) 2018-2020 Western Digital Corporation or its affiliates
 * Copyright (C) 2017-2018 Wearable, Inc.
 * Copyright (C) 2000-2012 leJOS Contributors
 * Copyright (C) 2000 Jose H. Solorzano and TinyVM Contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 * 
 * This Source Code Form is “Incompatible With Secondary Licenses”,
 * as defined by the Mozilla Public License, v. 2.0.
 */

package org.naniteproject;

import java.lang.*;
import org.naniteproject.NaniteEvent;

class Shutdown
{
    private final static int SHUTDOWN_EVENT = 1;
    private final static long WAIT_FOREVER = 0x7fffffffffffffffL;

    /**
     * This method waits for the system shutdown event, and then proceeds to
     * start the actual hooks..
     */

    private static void shutdownWait() {
        final NaniteEvent event = new NaniteEvent(NaniteEvent.SHUTDOWN);
        final Thread s = Thread.currentThread();
        
        s.setPriority(Thread.MAX_PRIORITY - 1);
        s.setDaemon(true);
        
        // We wait to be told to shut the system down
        try {
            event.waitEvent(0);
        } catch (InterruptedException e) {
            // If we get interrupted just give up...
            event.free();
            return;
        }
        // make sure we continue to run, even if other threads exit.
        s.setDaemon(false);

        // Invoke the shutdown events
        Runtime.getRuntime().exit(0);
    }
}
