class LocationReleasesController < ApplicationController
  include ProjectContext, LocationReleaseContext

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

  include ProjectLayout

  def index
    @location_releases = filtered_location_releases.order_by_recent.paginate(page: params[:page])
  end

  def new
    @location_release = build_location_release
  end

  def create
    @location_release = build_location_release(location_release_params)

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

  def edit
    @project = @location_release.project
  end

  def update
    @project = @location_release.project

    if @location_release.update(location_release_params)
      redirect_to [@project, :location_releases], notice: t(".notice")
    else
      render :edit
    end
  end

  def destroy
    @project = @location_release.project

    @location_release.destroy

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

  private

  def location_releases
    if @project
      policy_scope(@project.location_releases)
    else
      policy_scope(LocationRelease)
    end
  end

  def location_release_params
    params.require(:location_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,
      :contract, { photos: [] },
      :applicable_medium_id, :applicable_medium_text,
      :territory_id, :territory_text,
      :term_id, :term_text,
      :restriction_id, :restriction_text,
      :filming_started_on, :filming_ended_on,
      :filming_hours
    )
  end

  def build_location_release(attrs = {})
    authorize @project.location_releases.build(attrs)
  end

  def filtered_location_releases
    results = location_releases

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

    if params[:video_id].present?
      results = results.appearing_in(params[:video_id])
    end

    results
  end

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