require 'pathname'

class ChildDocument < ActiveRecord::Base
  
  self.table_name = 'gob_goe_com_detalle_estandares'
  self.primary_key = 'id'

  attr_accessible :titulo,
                  :descripcion,
                  :formato,
                  :url_archivo,
                  :estandar_id, # parent document id
                  :log_descarga,
                  :fecha,
                  :peso,
                  :migrated,
                  :attempts,
                  :error_message
end

class ParentDocument < ActiveRecord::Base
  
  self.table_name = 'gob_goe_com_estandares'
  self.primary_key = 'id'

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

  has_many :children_documents, class_name: ChildDocument, foreign_key: :estandar_id
end

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

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

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

def download_file(child_document)
  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} '#{child_document.url_archivo}'")
    system("wget -P #{download_to} '#{child_document.url_archivo}'")
  end
  if File.exists?(file_path(child_document))
    return true
  else
    child_document.error_message += "- wget fails\n"
    child_document.save
    return false
  end
end

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

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

def add_child_document_error_message_column
  begin
    ActiveRecord::Base.connection().execute("alter table #{ChildDocument.table_name} add error_message text not null")
  rescue
    puts "Was not possible add error_message column to #{ChildDocument.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 :children_documents do
  desc 'Migrate children documents'
  task :migrate, [:institution_id] => :environment do |tsk, args|
    add_child_document_migrated_column
    add_child_document_attempts_column
    add_child_document_error_message_column

    parent_documents = ParentDocument.where("hijos = 1 and id in (select estandar_id from gob_goe_com_detalle_estandares)")

    parent_documents.each do |parent_document|
      migrate_child_document(parent_document, args[:institution_id])
    end
  end
  
  task :destroy, [:institution_id] => :environment do |tsk, args|
    institution = Institution.find args[:institution_id]
    institution.document_categories.each do |document_category|
      document_category.destroy
    end
  end

end

def migrate_child_document(parent_document, institution_id)

  conditions = {
    name: parent_document.titulo,
    information_standard_id: new_standard_id(parent_document.categoria_id),
    institution_id: institution_id
  }

  document_category = DocumentCategory.where(conditions).first

  if document_category.nil?
    document_category = DocumentCategory.new(conditions)    
    document_category.save(validate: false)
  end

  parent_document.children_documents.where('migrated = 0').each do |child_document|

    document = Document.new
    document.document_category = document_category
    document.active = true
    document.institution_id = institution_id
    document.information_standard_id = new_standard_id(parent_document.categoria_id)
    document.name = child_document.titulo
    document.description = child_document.descripcion
    document.downloads = child_document.log_descarga
    document.created_at = child_document.fecha
    
    child_document.attempts += 1

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

  end
end