# == Schema Information
#
# Table name: sn_sources
#
#  id         :integer          not null, primary key
#  category   :string(255)      not null
#  sn         :string(255)      not null
#  created_at :datetime         not null
#  updated_at :datetime         not null
#
class SnSource < ApplicationRecord
  validates :sn, uniqueness: true, presence: true
  validates :category, presence: true
  SN_SOURCE = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]

  # @param category [String] eg: AS7
  def self.generate_content(category)
    raise "category null!" if category.blank?

    sn_val = category + SN_SOURCE.sample(5).join
    return nil if SnSource.where(:sn => sn_val).exists?

    sn_val
  end

  # @param image_count [Integer]
  # @param category [String] eg: AS7
  def self.batch_generate(image_count, category)
    raise "image_count invalid!" if image_count.nil? || image_count <= 0
    raise "category null!" if category.blank?

    store_dir = Rails.root.join("public/system/qrcodes", category).to_s
    meta_file = category + "_" + Time.now.strftime("%Y-%m-%d-%H-%M") + ".txt"
    meta_file_path = Rails.root.join("public/system/qrcodes", meta_file).to_s
    system("mkdir -p #{store_dir}")

    image_count.times do |i|
      index_s = i.to_s.rjust(6, "0")
      while true
        value = self.generate_content(category)
        if value.nil?
          next
        end
        #puts "#{i}: Generated value: #{value}"

        File.open("/tmp/qrencode_progress.txt", "w") do |f|
          f.puts("#{i}")
        end

        sn_source = SnSource.new(sn: value, category: category)
        sn_source.save

        file_name = Rails.root.join("public/system/qrcodes", category, "#{category}_#{sn_source.id}_#{value}.png")
        system("qrencode '#{value}' -o #{file_name} -s 10")
        system("convert #{file_name} -crop 234x234+28+28 #{file_name}")
        system("convert #{file_name} -resize 80x80       #{file_name}")
        File.open(meta_file_path, "a") do |f|
          f.puts(value)
        end
        break
      end
    end
  end

  def self.load_from_file(file_path)
    File.open(file_path, "r").each_line do |line|
      data = line.strip
      sn_source = SnSource.new(sn: data, category: "HM0")
      if sn_source.save
        puts "Success."
      end
    end
  end
end
