class ConsultantJob < ActiveRecord::Base
  self.table_name = 'goes_goe_pla_plaza'
  self.primary_key = 'pla_id'

  attr_accessible :pla_id,
    :pla_id_ins,
    :pla_id_pue,
    :pla_id_are,
    :pla_id_ins2,
    :pla_titulo,
    :pla_salario,
    :pla_dietas,
    :pla_descripcion,
    :pla_estado,
    :pla_id_tpl,
    :pla_id_ins3
end

class Consultant < ActiveRecord::Base
  self.table_name = 'goes_goe_fun_funcionario'
  self.primary_key = 'fun_id'

  attr_accessible :fun_id,
    :fun_id_ins,
    :fun_id_pla,
    :fun_nombres,
    :fun_apellidos,
    :fun_curriculum,
    :fun_alto_funcionario,
    :fun_tipo_cargo,
    :fun_estado,
    :fun_imagen

  belongs_to :consultant_job, foreign_key: :fun_id_pla, primary_key: :pla_id
  has_many :consultant_mails, foreign_key: :cxf_id_fun, primary_key: :fun_id
  has_many :consultant_phones, foreign_key: :txf_id_fun, primary_key: :fun_id

  delegate :pla_titulo, to: :consultant_job, prefix: :job, allow_nil: true
end

class ConsultantMail < ActiveRecord::Base
  self.table_name = 'goes_goe_cxf_correoxfuncionario'

  belongs_to :consultant, foreign_key: :cxf_id_fun, primary_key: :fun_id
  belongs_to :old_mail, foreign_key: :cxf_id_cor, primary_key: :cor_id

  delegate :cor_direccion, to: :old_mail, prefix: true, allow_nil: true
end

class OldMail < ActiveRecord::Base
  self.table_name = 'goes_goe_cor_correo'
  self.primary_key = 'cor_id'
end

class ConsultantPhone < ActiveRecord::Base
  self.table_name = 'goes_goe_txf_telefonoxfuncionario'

  belongs_to :consultant, foreign_key: :txf_id_fun, primary_key: :fun_id
  belongs_to :phone, foreign_key: :txf_id_tel, primary_key: :tel_id

  delegate :tel_numero, to: :phone, prefix: true, allow_nil: true
end

class Phone < ActiveRecord::Base
  self.table_name = 'goes_goe_tel_telefono'
  self.primary_key = 'tel_id'
end


def migrate_consultant_structure(consultant, institution_id)

  consultant.attempts += 1

  institution_consultant = InstitutionConsultant.new
  institution_consultant.institution_id = institution_id
  institution_consultant.name = [consultant.fun_nombres, consultant.fun_apellidos].join(", ")
  institution_consultant.job = consultant.job_pla_titulo
  institution_consultant.functions = ActionController::Base.helpers.sanitize(consultant.fun_curriculum, tags: %w(br)).strip.gsub('<br />', "\n") rescue ""
  institution_consultant.created_at = Time.current
  institution_consultant.updated_at = Time.current
  institution_consultant.active = consultant.fun_estado?
  institution_consultant.email = consultant.consultant_mails.map(&:mail_cor_direccion).join(", ") rescue ""
  institution_consultant.phone = consultant.consultant_phones.map(&:phone_tel_numero).join(", ") rescue ""

  if institution_consultant.save(validate: false)
    consultant.migrated = 1
  else
    consultant.error_message = "- #{institution_consultant.errors.map{ |name, message| "#{name}: #{message}" }.join("\n")}"
  end
  consultant.save

end

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

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

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

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

    add_consultant_migrated_column
    add_consultant_attempts_column
    add_consultant_error_message_column

    consultants = Consultant.where("IFNULL(fun_tipo_cargo, 0) = 1 AND migrated = 0 AND attempts < 3")

    consultants.each do |consultant|
      migrate_consultant_structure(consultant, args[:institution_id])
    end
  end

  task :destroy, [:institution_id] => :environment do |tsk, args|
    institution = Institution.find args[:institution_id]
    institution.institution_consultants.destroy_all
  end
end
