class AcquiredMediaReleasesController < ApplicationController
  include ProjectContext, AcquiredMediaReleaseContext

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

  include ProjectLayout

  def index
    @acquired_media_releases = filtered_acquired_media_releases.order_by_recent.paginate(page: params[:page])
  end

  def new
    @acquired_media_release = build_acquired_media_release
  end

  def create
    @acquired_media_release = build_acquired_media_release(acquired_media_release_params)

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

  def edit
    @project = @acquired_media_release.project
  end

  def update
    @project = @acquired_media_release.project

    if @acquired_media_release.update(acquired_media_release_params)
      redirect_to [@project, :acquired_media_releases], notice: t(".notice")
    else
      render :edit
    end
  end

  def destroy
    @project = @acquired_media_release.project
    @acquired_media_release.destroy
    redirect_to [@project, :acquired_media_releases], alert: t(".alert")
  end

  private

  def acquired_media_releases
    if @project
      policy_scope(@project.acquired_media_releases)
    else
      policy_scope(AcquiredMediaRelease)
    end
  end

  def acquired_media_release_params
    params.require(:acquired_media_release).permit(
      :name,
      :territory,
      :term,
      :person_first_name,
      :person_last_name,
      :person_phone,
      :person_email,
      :person_company,
      :person_title,
      :person_address_street1,
      :person_address_street2,
      :person_address_city,
      :person_address_state,
      :person_address_zip,
      :person_address_country,
      :contract,
      :applicable_medium_id, :applicable_medium_text,
      :territory_id, :territory_text,
      :term_id, :term_text,
      :restriction_id, :restriction_text,
      categories: [],
      file_infos_attributes: [
        :filename,
        :content_type,
        :byte_size
      ]
    )
  end

  def build_acquired_media_release(attrs = {})
    authorize @project.acquired_media_releases.build(attrs)
  end

  def filtered_acquired_media_releases
    results = acquired_media_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: AcquiredMediaRelease.to_s, user_agent: request.user_agent, user_ip: request.remote_ip)
  end
end
