/*
 * Copyright (c) 2002-2007 TeamDev Ltd. All rights reserved.
 *
 * Use is subject to license terms.
 *
 * The complete licence text can be found at
 * http://www.teamdev.com/winpack/license.jsf
 */
package com.jniwrapper.win32;

import com.jniwrapper.Bool;
import com.jniwrapper.Function;
import com.jniwrapper.Pointer;
import com.jniwrapper.win32.system.Kernel32;

/**
 * A base class for all handle types.
 *
 * @author Serge Piletsky
 */
public class Handle extends Pointer.Void
{
    private static final String FUNCTION_CloseHandle = "CloseHandle";

    /**
     * Constucts a blank handle instance.
     */
    public Handle()
    {
        super();
    }

    /**
     * Constructs a handle with the passed value.
     *
     * @param value handle value.
     */
    public Handle(long value)
    {
        super(value);
    }

    public Object clone()
    {
        return new Handle(this.getValue());
    }

    /**
     * Closes the opened object handle. This method closes handles to the following objects:
     * <ul>
     *  <li>Access token</li>
     *  <li>Communications device</li>
     *  <li>Console input</li>
     *  <li>Console screen buffer</li>
     *  <li>Event</li>
     *  <li>File</li>
     *  <li>File mapping</li>
     *  <li>Job</li>
     *  <li>Mailslot</li>
     *  <li>Memory resource notification</li>
     *  <li>Mutex</li>
     *  <li>Named pipe</li>
     *  <li>Pipe</li>
     *  <li>Process</li>
     *  <li>Semaphore</li>
     *  <li>Socket</li>
     *  <li>Thread</li>
     *  <li>Waitable timer</li>
     * </ul>
     *
     * @param handle handle to an opened object
     * @return if the function succeeds, the return value is true; otherwise - false. 
     */
    public static boolean closeHandle(Handle handle)
    {
        if (handle == null || handle.isNull())
        {
            throw new IllegalArgumentException();
        }
        Function function = Kernel32.getInstance().getFunction(FUNCTION_CloseHandle);
        Bool functionResult = new Bool();
        function.invoke(functionResult, handle);
        return functionResult.getValue();
    }
}
