class ConvertIsbn < ActiveRecord::Migration
  def self.up
    add_column :books, :new_isbn, :string, :limit => 13
    Book.find(:all).each do |book|  
      Book.update(book.id, :new_isbn => convert_isbn(book.isbn))
    end
  end

  def self.down
    remove_column :books, :new_isbn
  end

  # Konwersja z 10-cio na 13-cyfrowy format ISBN
  def self.convert_isbn(isbn)
    isbn.gsub!('-','')
    isbn = ('978'+isbn)[0..-2]
    x = 0   
    checksum = 0
    (0..isbn.length-1).each do |n|
      wf = (n % 2 == 0) ? 1 : 3 
      x += isbn.split('')[n].to_i * wf.to_i 
    end
    if x % 10 > 0
      c = 10 * (x / 10 + 1) - x
      checksum = c if c < 10
    end
    return isbn.to_s + checksum.to_s
  end
end