class InformationRequestEvent < ActiveRecord::Base
# Accessibles
attr_accessible :state, :justification, :user_id, :event_start
# for non table fields
attr_accessible :delivery_deadline, :extension_type, :information_type,	:resolution_type, :redirected_id
attr_accessible :update_admitted, :redirect, :update_closed

# Accessors
attr_accessor :delivery_deadline, :extension_type, :information_type,	:resolution_type, :redirected_id, :update_admitted
attr_accessor :redirect, :update_closed

# Associations
belongs_to :eventable, polymorphic: true
belongs_to :user

# Validations
validates :eventable_id, :eventable_type, :user_id, :state, :justification, presence: true
validates :state, inclusion: { in: InformationRequest::STATES }
# validate if state is process and parent is a information request
validates :extension_type, :delivery_deadline, presence: true, if: Proc.new{|o| ['process','extended'].include?(o.state) and o.eventable.is_a?(InformationRequest)}
# validate if state is closed and parent is a comment or parent is a information request, if is a information request shouldn't have requirements
#validates :information_type, :resolution_type, presence: true, if: Proc.new{|o| o.state == 'closed' and ( o.eventable.is_a?(InformationRequest) and !o.eventable.has_requirements? ) }
#validate :resolution_type_redirected, if: Proc.new{|o| o.resolution_type == 'art_67_laip' or o.redirect?} # trigger custom validates if resolution is redirected
validate :event_start_less_than_today, if: Proc.new{|o| ['process', 'closed'].include?(o.state) }

# Delegates
delegate :name, :avatar, to: :user, allow_nil: true, prefix: true
delegate :institution_id, to: :eventable, allow_nil: true, prefix: false

# Callbacks
after_create :update_parent_with_process, if: Proc.new{|o| ['process','extended'].include?(o.state) and o.eventable.is_a?(InformationRequest)}
after_create :update_parent_with_closed, if: Proc.new{|o| ['closed','not_admitted','not_corrected'].include?(o.state)}
after_create :update_parent_with_state
#after_create :update_parent_with_correct, if: Proc.new{|o| o.state=='correct' and o.eventable.is_a?(InformationRequest)}

# Methods
def event_start_less_than_today
  if event_start > Date.current and state == 'process'
    errors.add :delivery_deadline, I18n.t('errors.models.information_request.attributes.event_start.less_than_today')
  elsif event_start > Date.current and state == 'closed'
    errors.add :justification, I18n.t('errors.models.information_request.attributes.event_start.less_than_today')
  end
end

def resolution_type_redirected
  if redirected_id.blank?
    errors.add :redirected_id, I18n.t('errors.models.information_request.attributes.redirected_institution_id.present')
  #elsif eventable.commentable.opened_requirements > 1
    #errors.add :redirected_id, I18n.t('errors.models.information_request.attributes.redirected_institution_id.too_many_opened_requirements')
  end
end

def self.with_last_state(state, klass = 'InformationRequest')
  where("information_request_events.id IN (SELECT MAX(id) FROM information_request_events WHERE eventable_type = :klass GROUP BY eventable_id) AND state in (:state) AND eventable_type = :klass", state: Array.wrap(state), klass: klass)
end

def self.without_last_state(state, klass = 'InformationRequest')
  where("information_request_events.id IN (SELECT MAX(id) FROM information_request_events WHERE eventable_type = :klass GROUP BY eventable_id) AND state not in (:state) AND eventable_type = :klass", state: Array.wrap(state), klass: klass)
end

def business_days_passed(end_date = Date.current)
  days = 0
  date = event_start + 1.day
  while date <= end_date
    days = days + 1 unless date.saturday? or date.sunday?
    date = date + 1.day
  end
  days
end

def event_start_with_business_days_added(days = 0)
  business_date = event_start
  # obtain all business days
  business_days = CalendarEvent.select('kind,start_at').joins(:institution_calendar).where('institution_calendars.institution_id = ? AND calendar_events.start_at > ?', institution_id, business_date.beginning_of_day).group_by{|o| o.start_at.to_date}
  while days > 1 # 0 first business day is current day
    business_date = business_date + 1.day
    if business_days.has_key?(business_date)
      # rest a day unless is a holiday
      days -= 1 unless business_days[business_date].map(&:kind).include?(:holiday)
    else
      # rest a day unless is weekened
      days -= 1 unless business_date.saturday? or business_date.sunday?
    end
  end
  business_date
end

def update_parent_with_process
  parent = eventable
  parent.assign_attributes(delivery_deadline: delivery_deadline, extension_type: extension_type)
  parent.save(validate: false)
  parent.update_column(:admitted_at, Time.zone.local(event_start.year,event_start.month,event_start.day,Time.current.hour,Time.current.min,Time.current.sec)) if update_admitted.to_i == 1
end

def update_parent_with_closed
  if eventable.is_a?(Comment)
    # eventable is a comment and requirement is redirected, we close the request and re-send it to the new institution
    #clone_request if resolution_type == 'art_67_laip'
  elsif eventable.is_a?(InformationRequest)
    #clone_request if redirect?
    if update_closed.to_i == 1
      update_column(:created_at, Time.zone.local(event_start.year,event_start.month,event_start.day,Time.current.hour,Time.current.min,Time.current.sec))
      update_column(:updated_at, Time.zone.local(event_start.year,event_start.month,event_start.day,Time.current.hour,Time.current.min,Time.current.sec))
    end
  end
end

def update_parent_with_state
  parent = eventable
  parent.update_column(:state, state)
end

def clone_request
  request = eventable.is_a?(Comment) ? eventable.commentable : eventable
  #request.events.create(state: 'closed', justification: I18n.t('label.closed_by_redirected'), user_id: parent.user_id)
  # dup the information request
  new_request = request.dup
  new_request.redirected_institution_id = new_request.institution_id
  new_request.institution_id = redirected_id
  new_request.state_id = new_request.city.state_id rescue nil
  new_request.skip_textcaptcha = true
  new_request.document_front_image = request.document_front_image
  new_request.document_back_image = request.document_back_image
  new_request.delivery_deadline = nil
  new_request.extension_type = nil
  new_request.information_type = nil
  new_request.resolution_type = nil
  new_request.correlative = nil
  new_request.delivery_deadline = nil
  #new_request.set_correlative
  new_request.confirmed_at = Time.current
  new_request.admitted_at = nil
  if new_request.save
    c = new_request.comments.new
    if eventable.is_a?(Comment)
      c.message = "Solicitud redireccionada desde #{request.institution.try(:name)}, con el siguiente detalle:\n#{eventable.message}"
    else
      c.message = "Solicitud redireccionada desde #{request.institution.try(:name)}, con el siguiente detalle:\n#{justification}"
    end
    c.user_id = user_id
    c.save
    new_request.deliver_information_request
  end
end

def redirect?
  redirect.to_i == 1
end

def percent deadline
  total_days = (deadline - self.event_start).to_i
  passed_days = (deadline - (Date.current + 2.day)).to_i
  progress = ((passed_days * 100) / total_days).ceil
  progress = 100 if progress > 100
  progress = -100 if progress < -100
  progress
end

# for attr_accesor with dates
columns_hash["delivery_deadline"] = ActiveRecord::ConnectionAdapters::Column.new("delivery_deadline", nil, "date")
end
