# frozen_string_literal: true

require "ffi"

module Libptouch
  module Binding
    extend FFI::Library

    def self.library_files
      list = []
      env = ENV["LIBPTOUCH_LIB"]
      list << env if env && !env.empty?
      base = File.expand_path("../../..", __dir__)
      %w[libptouch.so libptouch.dylib].each do |name|
        path = File.join(base, "build", name)
        list << path if File.file?(path)
      end
      list << "libptouch"
      list
    end

    ffi_lib library_files

    class RasterParams < FFI::Struct
      layout :width_dots, :uint32,
             :height_dots, :uint32,
             :margin_mm, :uint8,
             :_pad, [:uint8, 3]
    end

    class PngOptions < FFI::Struct
      layout :threshold, :uint8
    end

    attach_function :libptouch_create, [], :pointer
    attach_function :libptouch_destroy, [:pointer], :void
    attach_function :libptouch_strerror, [:pointer], :string
    attach_function :libptouch_last_error, [:pointer], :int
    attach_function :libptouch_open_usb, [:pointer], :int
    attach_function :libptouch_open_usb_vid_pid, %i[pointer uint16 uint16], :int
    attach_function :libptouch_close, [:pointer], :void
    attach_function :libptouch_check_raster, %i[pointer pointer size_t pointer], :int
    attach_function :libptouch_print_raster, %i[pointer pointer size_t pointer], :int
    attach_function :libptouch_png_file_to_raster,
                    %i[pointer string pointer pointer pointer pointer], :int
    attach_function :libptouch_free_raster, [:pointer], :void
    attach_function :libptouch_get_status, %i[pointer pointer], :int
  end
end
