# frozen_string_literal: true
#
class ExpedientsController < ApplicationController

  def create
    @expedient = Expedient.new item_params
    @expedient.confirmed_at = Time.current
    @expedient.received_at = Time.current
    @expedient.entry_way_id = EntryWay.ga.first.try(:id)
    if Rails.env.production?
      success = verify_recaptcha(model: @expedient, message: 'Por favor marque la opción "No soy un robot"') && @expedient.save
    else
      success = @expedient.save
    end

    respond_to do |format|
      format.html {
        if success
          redirect_to thanks_expedient_url(@expedient) and return
        else
          @institutions = Institution.visible.includes(:branches)
          @states = State.includes(:cities)
          render template: 'home/index'
        end
      }
      format.json {
        if success
          # Save assets
          if params[:file]
            params[:file].each do |k, file|
              Asset.create attachment: file, assetable: @expedient
            end
          end
          render json: {code: 200, item: @expedient, redirect_url: thanks_expedient_url(@expedient)}
        else
          render json: {code: 422, errors: @expedient.errors}
        end
      }
    end
  end

  def thanks
    @expedient = Expedient.find params[:id]
    @institution = @expedient.institution
  end

  def verify
    @events = []
    @expedient = Expedient.where(reference_code: params[:code].try(:strip).try(:upcase)).first
    if @expedient
      @events << { state: 'received', user_id: 1, datetime: @expedient.created_at, text: @expedient.comment }
      while @expedient.events.pluck(:state).include?('redirected')
        e = @expedient.events.where(state: 'redirected').first
        @expedient = Expedient.where(expedient_id: @expedient.id).first
        @events << { state: 'redirected', user_id: e.user_id, datetime: e.created_at, text: e.justification, institution: @expedient.institution.try(:name) }
      end
      if @expedient.new?
        if @expedient.events.failed_attempts.any?
          @expedient.events.failed_attempts.each do |ev|
            @events << { state: 'failed_attempt', user_id: ev.user_id, datetime: ev.created_at, text: ev.justification }
          end
        end
        @events << { state: 'admitted', user_id: nil, datetime: nil, text: nil }
        @events << { state: 'process', user_id: nil, datetime: nil, text: nil }
        @events << { state: 'resolution', user_id: nil, datetime: nil, text: nil }
        @events << { state: 'closed', user_id: nil, datetime: nil, text: nil }
      elsif @expedient.process?
        e = @expedient.events.where(state: 'process').last
        if @expedient.events.failed_attempts.any?
          @expedient.events.failed_attempts.each do |ev|
            @events << { state: 'failed_attempt', user_id: ev.user_id, datetime: ev.created_at, text: ev.justification }
          end
        end
        @events << { state: 'admitted', user_id: e.user_id, datetime: e.created_at, text: e.justification }
        @events << { state: 'process', user_id: nil, datetime: nil, text: nil }
        @events << { state: 'resolution', user_id: nil, datetime: nil, text: nil }
        @events << { state: 'closed', user_id: nil, datetime: nil, text: nil }
      else
        e = @expedient.events.where(state: 'process').last
        if @expedient.events.failed_attempts.any?
          @expedient.events.failed_attempts.each do |ev|
            @events << { state: 'failed_attempt', user_id: ev.user_id, datetime: ev.created_at, text: ev.justification }
          end
        end
        if e
          @events << { state: 'admitted', user_id: e.user_id, datetime: e.created_at, text: e.justification }
          @events << { state: 'process', user_id: e.user_id, datetime: nil, text: nil }
        end
        e = @expedient.events.where(state: 'closed').last
        if e
          @events << { state: 'resolution', user_id: e.user_id, datetime: e.created_at, text: e.justification }
          @events << { state: 'closed', user_id: e.user_id, datetime: nil, text: nil }
        end
      end
      @institution = @expedient.try(:institution)
      @expedient.update_column(:tracking_count, @expedient.tracking_count + 1) unless user_signed_in?
    end

    @events_states = @events.inject(Hash.new(0)) {|s, e| (e[:datetime].nil? ? nil : (s[e[:state]] += 1)) ; s}
  end

  def item_params
    params.require(:expedient).permit(
      :comment,
      :institution_id,
      :contact,
      :phone,
      :email,
      :age,
      :gender,
      :state_id,
      :city_id,
      :branch_id,
      :anonymous,
      :happened_at,
      :place,
      :national_license_plate,
      :personnel_name,
      :process_name
    )
  end
end
