local basexx = require 'basexx'
local uuid = require 'lua_uuid'
local vips = require 'vips'
local thumbnail = require './models/thumbnail'

local image = {}

-- where images are saved:
--image.directory = 'thumbnails/'

image.setdb = function(db)
  image.db = db
end

image.new = function(img_buffer, original_filename)
  local image_record = {};
  image_record['type'] = 'image'
  image_record.original_filename = original_filename
  
  local new_filename = uuid()
  --local vips_image = vips.Image.new_from_buffer(img_buffer, "", {access = "sequential"})
  local thumbnail_original = vips.Image.new_from_buffer(img_buffer, "")  -- don't give `{access = "sequential"}` option as 3rd parameter, since then it won't be able to be read twice: once for 960px thumbnail, and again for the 180px
  local thumbnail_960 = thumbnail_original:thumbnail_image(960)
  local thumbnail_180 = thumbnail_original:thumbnail_image(180)
  
  --[[
  thumbnail_original:write_to_file(thumbnail_original_path, {compression=9}) -- LMDBTODO: instead of writing to file, store in record; store each thumbnail in individual records (type='thumbnail'), so binser doesn't have to deserialize all the sizes just to get one (small) size
  thumbnail_960:write_to_file(thumbnail_960_path, {compression=9})
  thumbnail_180:write_to_file(thumbnail_180_path, {compression=9})
  ]]
  
  local thumbnail_original_record = thumbnail.newfromvips(thumbnail_original)
  local thumbnail_960_record = thumbnail.newfromvips(thumbnail_960)
  local thumbnail_180_record = thumbnail.newfromvips(thumbnail_180)
  
  -- TODO: close/release vips buffers, unless vips binding does it automatically
  
  image_record.thumbnail_original_id = thumbnail_original_record.id
  image_record.thumbnail_960_id = thumbnail_960_record.id
  image_record.thumbnail_180_id = thumbnail_180_record.id
  
  if image.db ~= nil then
    image.db:insertrecord(image_record)
  end
  
  return image_record;
end

image.new_from_base64 = function(img_base64, original_filename)
  local img_buffer = basexx.from_base64(img_base64)
  return image.new(img_buffer, original_filename);
end

return image;
