require 'pathname'

class Component < ActiveRecord::Base
  
  self.table_name = 'gob_goe_com_estandares'

  attr_accessible :titulo,
                  :descripcion,
                  :url_archivo,
                  :categoria_id,
                  :portada,
                  :archivo,
                  :fecha,
                  :estado,
                  :formato,
                  :peso,
                  :log_descarga,
                  :hijos,
                  :migrated,
                  :attempts,
                  :error_message
end

def download_to
  Rails.root.join('tmp')
  #'/tmp'
end

def file_path(component)
  File.join(download_to, filename(component.url_archivo))  
end

def filename(url)
  Pathname.new(url).basename
end

def download_file(component)
  begin
    #system("wget -d --header=\"User-Agent: Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11\" --header=\"Referer: http://gobiernoabierto.gob.sv/\" --header=\"Accept-Encoding: compress, gzip\" -c --tries=3 --timeout=60 -P #{download_to} '#{component.url_archivo}'")
    system("wget -P #{download_to} '#{component.url_archivo}'")
  end
  if File.exists?(file_path(component))
    return true
  else
    component.error_message += "- wget fails\n"
    component.save
    return false
  end
end

def is_component_active?(component)
  component.estado == 'Activo'
end

def migrate_document(component, institution_id)

  component.attempts += 1

  document = Document.new
  document.active = is_component_active?(component)
  document.institution_id = institution_id
  document.information_standard_id = new_standard_id(component.categoria_id)
  document.name = component.titulo
  document.description = component.descripcion
  document.downloads = component.log_descarga
  document.created_at = component.fecha

  if download_file(component)
    document.datafile = File.open(file_path(component))
    if document.save(validate: false)
      component.migrated = 1
      File.delete(file_path(component))
    else
      component.error_message = "- #{document.errors.map{ |name, message| "#{name}: #{message}" }.join("\n")}"
    end
    component.save
  end
end

def add_migrated_column
  begin
    ActiveRecord::Base.connection().execute("alter table #{Component.table_name} add migrated int(1) default 0")
  rescue
    puts "Was not possible add migrated column to #{Component.table_name} table"
  end
end

def add_attempts_column
  begin
    ActiveRecord::Base.connection().execute("alter table #{Component.table_name} add attempts int(1) default 0")
  rescue
    puts "Was not possible add attempts column to #{Component.table_name} table"
  end
end

def add_error_message_column
  begin
    ActiveRecord::Base.connection().execute("alter table #{Component.table_name} add error_message text not null")
  rescue
    puts "Was not possible add error_message column to #{Component.table_name} table"
  end
end

def new_standard_id(old_id)
  ids = {}
  ids[1] = 1
  ids[2] = 2
  ids[3] = 3
  ids[4] = 4
  ids[5] = 5
  ids[6] = 6
  ids[7] = 7
  ids[8] = 8
  ids[9] = 9
  ids[10] = 10
  ids[11] = 11
  ids[12] = 12
  ids[13] = 26
  ids[14] = 14
  ids[15] = 15
  ids[16] = 16
  ids[17] = 17
  ids[18] = 18
  ids[19] = 29
  ids[20] = 20
  ids[21] = 21
  ids[22] = 22
  ids[23] = 23
  ids[24] = 24
  ids[25] = 25
  ids[26] = 26
  ids[27] = 27
  ids[28] = 28
  ids[29] = 29
  ids[30] = 30
  ids[31] = 31
  ids[32] = 16
  ids[33] = 13
  ids[34] = 25
  ids[35] = 27
  ids[old_id]
end

namespace :documents do
  desc 'Migrate documents'
  task :migrate, [:institution_id] => :environment do |tsk, args|
    add_migrated_column
    add_attempts_column
    add_error_message_column

    components = Component.where("trim(url_archivo) != '' and migrated = 0 and attempts < 3")

    components.each do |component|
      migrate_document(component, args[:institution_id])
    end
  end
  
  task :destroy, [:institution_id] => :environment do |tsk, args|
    institution = Institution.find args[:institution_id]
    institution.documents.each do |document|
      document.destroy
    end
  end
end