class DirectoriesController < ApplicationController
  before_action :set_project
  before_action :build_directory, only: [:new, :create]
  before_action :set_directory, except: [:new, :create]

  layout "project"

  breadcrumb -> { t("shared.files") }, -> { @project }, match: :exact
  breadcrumb -> { @directory.name.titleize }, -> { [@project, @directory] }, match: :exact, except: [:new, :create]

  def new
  end

  def create
    @directory.attributes = directory_params_with_user

    if @directory.save
      log_create_analytics
      redirect_to [@project, @directory], notice: "The folder has been created"
    else
      render :new
    end
  end

  def show
    @files = filtered_files.paginate(page: params[:page])
  end

  def edit
  end

  def update
    if @directory.update(directory_params)
      redirect_to [@project, @directory], notice: t(".notice")
    else
      render :edit
    end
  end

  def destroy
    @directory.destroy
    redirect_to @project, alert: t(".alert")
  end

  def new_file
  end

  def destroy_file
    file = ActiveStorage::Attachment.find(params[:file_id])
    file.purge
    redirect_to [@project, @directory], alert: t(".alert")
  end

  private

  def filtered_files
    results = @directory.files

    if params[:query].present?
      results = @directory.search_files(params[:query])
    end

    results
  end

  def set_project
    @project = policy_scope(Project).find(params[:project_id])
  end

  def set_directory
    @directory = authorize policy_scope(Directory).find(params[:id])
  end

  def build_directory
    @directory = authorize @project.directories.build
  end

  def directory_params_with_user
    directory_params.merge(user: current_user)
  end

  def directory_params
    params.require(:directory).permit(:name, :category, :permissions, files: [])
  end

  def log_create_analytics
    TrackAnalyticsJob.perform_later(Current.user, Current.account, :track_create_custom_folder, user_agent: request.user_agent, user_ip: request.remote_ip)
  end
end
