class OrganizationChart < ActiveRecord::Base

  self.table_name = 'goes_goe_are_area'
  self.primary_key = 'are_id'

  attr_accessible :are_id,
    :are_id_ins,
    :are_titulo,
    :are_ubicacion,
    :are_padre,
    :are_descripcion,
    :migrated,
    :attempts,
    :error_message

  has_many :organization_charts, foreign_key: :are_padre
end

def migrate_structure(organization_chart, parent, institution_id)

  organization_chart.attempts += 1

  structure = InstitutionOrganizationalStructure.new
  structure.institution_id = institution_id
  structure.name = organization_chart.are_titulo
  structure.location = organization_chart.are_ubicacion
  structure.description = organization_chart.are_descripcion
  structure.created_at = Time.current
  structure.updated_at = Time.current
  
  if parent.nil?
    structure.institution_organizational_structure_id = nil 
  else
    structure.institution_organizational_structure_id = parent.id
  end

  if structure.save
    organization_chart.migrated = 1
  else
    organization_chart.error_message = "- #{structure.errors.map{ |name, message| "#{name}: #{message}" }.join("\n")}"
  end
  organization_chart.save
  
  if organization_chart.organization_charts.any?
    organization_chart.organization_charts.each do |child|
      migrate_structure(child, structure, institution_id)
    end
  end

end

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

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

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

namespace :organization_charts do
  desc 'Migrate institution_organizational_structures'
  task :migrate, [:institution_id] => :environment do |tsk, args|

    add_migrated_column
    add_attempts_column
    add_error_message_column

    organization_charts = OrganizationChart.where("IFNULL(are_padre, 0) = 0 AND migrated = 0 AND attempts < 3")

    organization_charts.each do |organization_chart|
      migrate_structure(organization_chart, nil, args[:institution_id])
    end
  end
  
  task :destroy, [:institution_id] => :environment do |tsk, args|
    institution = Institution.find args[:institution_id]
    institution.institution_organizational_structures.each do |institution_organizational_structure|
      institution_organizational_structure.destroy
    end
  end
end