class ProjectsController < ApplicationController
  include ProjectContext

  layout "project", only: [:show]

  before_action :set_project, only: [:show, :edit, :update, :destroy]

  def index
    @projects = policy_scope(Current.account.projects).order_by_name
  end

  def new
    @project = build_project
  end

  def create
    @project = build_project(project_params_with_current_account)

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

  def show
    @directories = policy_scope(@project.directories).order_by_name
  end

  def edit
  end

  def update
    if @project.update(project_params)
      redirect_to @project, notice: "The project has been updated"
    else
      render :edit
    end
  end

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

  private

  def set_project
    @project = authorize projects.find(params[:id])
  end

  def build_project(params = {})
    authorize projects.build(params.merge(account: Current.account))
  end

  def project_params
    params.require(:project).permit(:client_name, :description, :details, :name, :producer_address, :producer_name,
                                    :predefined_client_name, features_settings: features_settings_params)
  end

  def features_settings_params
    %i(appearance_release location_release material_release acquired_media_release music_release talent_release medical_release video_analysis)
  end

  def project_params_with_current_account
    project_params.merge(account: Current.account)
  end

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