class MaterialReleasesController < ApplicationController
  include ProjectContext

  before_action :set_project, only: [:index, :new, :create]
  before_action :set_material_release, only: [:edit, :update, :destroy]

  include ProjectLayout

  def index
    @material_releases = filtered_material_releases.order_by_recent.paginate(page: params[:page])
  end

  def new
    @material_release = build_material_release
  end

  def create
    @material_release = build_material_release(material_release_params)

    if @material_release.save
      log_create_analytics
      SetTagsForReleasableJob.perform_later(@material_release)
      redirect_to [@project, :material_releases], notice: t(".notice")
    else
      render :new
    end
  end

  def edit
    @project = @material_release.project
  end

  def update
    @project = @material_release.project

    if @material_release.update(material_release_params)
      redirect_to [@project, :material_releases], notice: t(".notice")
    else
      render :edit
    end
  end

  def destroy
    @project = @material_release.project

    @material_release.destroy

    redirect_to [@project, :material_releases], alert: t(".alert")
  end

  private

  def material_release_params
    params.require(:material_release).permit(
      :name, :address_street1, :address_street2, :address_city, :address_state, :address_zip, :address_country,
      :person_first_name, :person_last_name, :person_title, :person_company, :person_phone, :person_email,
      :person_address_street1, :person_address_street2, :person_address_city, :person_address_state, :person_address_zip, :person_address_country,
      :applicable_medium_id, :applicable_medium_text,
      :territory_id, :territory_text,
      :term_id, :term_text,
      :restriction_id, :restriction_text,
      :description,
      :contract, { photos: [] }
    )
  end

  def material_releases
    if @project
      policy_scope(@project.material_releases)
    else
      policy_scope(MaterialRelease)
    end
  end

  def build_material_release(attrs = {})
    authorize @project.material_releases.build(attrs)
  end

  def set_material_release
    @material_release = authorize material_releases.find(params[:id])
  end

  def filtered_material_releases
    results = material_releases

    if params[:query].present?
      results = results.search(params[:query])
    end

    results
  end

  def log_create_analytics
    TrackAnalyticsJob.perform_later(Current.user, Current.account, :track_create_non_native_release, release_type: MaterialRelease.to_s, user_agent: request.user_agent, user_ip: request.remote_ip)
  end
end
