# frozen_string_literal: true

require 'json'
require 'time'

module Staff
  class ActivityController < Staff::BaseController
    before_action :authorize_action

    def index
      parse_params
      set_member
      return if performed?
      set_logs
    end

    protected

    def authorize_action
      authorize Member
    end

    def set_member
      @member = Member.find params[:member_id]
      unless @member.errors.empty?
        flash[:warning] = 'User may be partially loaded.'
        flash[:error] = @member.errors
      end
    end

    def set_logs
      data = @member.activity_logs(@query_options)
      @logs = data[:items].each do |x|
        if x[:rails_params]
          x[:rails_params_pretty] = JSON.pretty_generate(x[:rails_params])
        end
      end

      if data[:next]
        @next_params = params.slice(
          :search, :member_id
        ).merge(
          continue: JSON.generate(data[:next])
        ).permit(:continue, :search, :member_id)
      end
    end

    def parse_params
      search = params.fetch(:search, {})
      @query_options = [:before_date, :after_date].each_with_object({}) do |x, m|
        if search[x] && !search[x].empty?
          m[x.to_sym] = Time.strptime(search[x], '%m/%d/%Y')
        end
      end
      if search[:text_query]
        @query_options[:text_query] = search[:text_query] unless search[:text_query].empty?
      end

      if params[:continue]
        c = JSON.parse(params[:continue])
        @query_options[:continue] = {
          user_id: c['user_id'],
          access_date: Time.parse(c['access_date'])
        }
      end
      if @query_options[:continue]
        @from = @query_options[:continue][:access_date]
      end
    end
  end
end
