#!/usr/bin/env ruby

ENV['RAILS_ENV'] ||= 'development'
require File.dirname(__FILE__) + '/../config/environment'

# import images from old presta shop
# images needs to be stored in public/tmp/original
class PsImage < ApplicationRecord
  self.table_name = 'ps_image'
  establish_connection :prestashop_old
end

ps_images = PsImage.order('id_image')
path = "#{Rails.root}/public/tmp/original/"
ps_images.each do |pi|
  file = "#{path}#{pi.id_product}-#{pi.id_image}.jpg"
  puts "#{file} - #{File.exist?(file)}"
  next unless File.exist?(file)
  image = Image.new
  f = File.open(file)
  image.image = f
  f.close
  image.imageable_type = 'Product'
  image.imageable_id = pi.id_product
  image.position = pi.position
  image.cover = pi.cover
  image.updated_by = 1
  image.active = true
  if image.save
    puts "saved: #{image.id}"
  else
    puts image.errors.full_messages
  end
end
