# frozen_string_literal: true
module Panel
  #
  class EventsController < PanelController
    include Panel::Crud
    include Panel::Multiple

    def model
      Event
    end

    def permits
      [:start_at, :justification, :state, :failed_attempt, :classification_type, :resolution_type, :it_proceeds, :response]
    end

    def exportable_fields
      []
    end

    def create
      @item = Expedient.find params[:expedient_id]
      @event = @item.events.new(item_params)
      if @event.failed_attempt.to_i == 1
        @event.state = 'failed_communication_attempt'
      else
        case @item.state
        when 'new'
          @event.state = 'process'
          @event.state = 'closed' if @event.classification_type.present?
        when 'process'
          @event.state = 'closed'
        end
      end
      @event.user_id = current_user.id

      success = @event.save
      respond_to do |format|
        format.html {
          if success
            if (@event.state == 'process') and (@item.events.where(state: 'process').any? and @item.anonymous == false)
              start_at = @item.received_at
              contact_at = @event.start_at
              @item.update_column(:contact_business_days, start_at.to_date.business_days_until(contact_at.to_date))
              @item.update_column(:contact_business_hours, start_at.business_time_until(contact_at).to_f/60/60)
            elsif @event.state == 'closed'
              @item.save!
            end
            return redirect_to(panel_expedient_url(@item), flash: {saved: true})
          else
            @errors = @event.errors
            @management = @item.managements.new
            @tags = ActsAsTaggableOn::Tag.for_context(:tags)
            @managements    = @item.managements.reorder(created_at: :asc)
            render 'panel/expedients/show'
          end
        }
      end
    end

    def update
      @item = Expedient.find params[:expedient_id]
      @event = Event.find params[:id]
      @event.assign_attributes(item_params)
      if @event.valid?
        @event.update_column(:justification, params[:event][:justification])
        @item.update_columns(
          classification_type: params[:event][:classification_type],
          response: params[:event][:response],
          resolution_type: params[:event][:resolution_type],
          it_proceeds: params[:event][:it_proceeds]
        )
      end
      return redirect_to(panel_expedient_url(@item, anchor: 'close-expedient-area'), flash: {saved: true})
    end

    def item_params
      perms = params.require(:event).permit(permits)
      perms
    end


  end
end
