/*
 * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
 */

package com.sun.glass.ui.x11;

import com.sun.glass.ui.Application;
import com.sun.glass.ui.Pixels;
import com.sun.glass.utils.Disposer;
import com.sun.glass.utils.DisposerRecord;

import java.nio.ByteBuffer;
import java.nio.IntBuffer;

public class X11Pixels extends Pixels {
    static {
        X11Application.initLibrary();
    }

    protected X11Pixels(int width, int height, ByteBuffer data) {
        super(width, height, data);
        Disposer.addRecord(this, this.disposerRecord = new PixelsDisposerRecord(ptr));
    }

    protected X11Pixels(int width, int height, IntBuffer data) {
        super(width, height, data);
        Disposer.addRecord(this, this.disposerRecord = new PixelsDisposerRecord(ptr));
    }

    static int getNativeFormat_impl() {
        return Pixels.Format.BYTE_BGRA_PRE;
    }

    private long ptr = 0; // native handle

    private final PixelsDisposerRecord disposerRecord;
    private static class PixelsDisposerRecord implements DisposerRecord {
        //close() sets this ptr to 0L
        public volatile long ptr;

        public PixelsDisposerRecord(long ptr) {
            this.ptr = ptr;
        }

        @Override public void dispose() {
            if (this.ptr != 0L) {
                _close(this.ptr);
            }
        }
    }

    private native long _create(int width, int height);
    private static native void _close(long ptr);

    @Override native protected void _fillDirectByteBuffer(ByteBuffer bb);
    @Override native protected void _attachInt(long ptr, int w, int h, IntBuffer ints, int[] array, int offset);
    @Override native protected void _attachByte(long ptr, int w, int h, ByteBuffer bytes, byte[] array, int offset);
}
