require 'digest/sha1'
class LightBox < ActiveRecord::Base
  belongs_to :user
  belongs_to :title
  has_many   :light_box_images, dependent: :destroy
  has_many   :images, through: :light_box_images
  before_create :generate_hash_code
  after_destroy :recreate_first_light_box

  validates :name, presence: true, uniqueness: { scope: :user_id, case_sensitive: false }
  validates :user_id,  presence: true
  validates :title_id, presence: true

  def recreate_first_light_box
    self.class.create(name: I18n.t('light_box.name'),
                      title_id: self.title_id,
                      user_id: self.user_id)  if self.class.where(user_id: self.user_id).count == 0
  end

  def self.export_to_csv(lightbox, session_provhd)
    export = ''
    export.encode!('UTF-8')
    CSV(export, {col_sep: ';'}) do |csv|
      i = 0
      csv << ["#{I18n.t('light_box.name')} '#{lightbox.name}'"]
      lightbox_images =  lightbox.images.where(content_error: 0)
      lightbox_images.each do |m|
        if session_provhd[m.provider_id]==1
          csv << [m.original_filename]
          i += 1
        end
      end
      csv << [I18n.t(:export_empty)] if i==0
    end
    export
  end

  private

  def generate_hash_code
    self.hash_code = "X#{Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join )}"
  end

end