class Public::LocationReleasesController < Public::BaseController
  include CreateReleasableJobs
  before_action :set_account, :set_project, :set_contract_template

  def new
    @location_release = build_location_release
  end

  def create
    @location_release = build_location_release(location_release_params_with_locale_and_contract_template)

    if @location_release.save(context: :native)
      log_create_analytics
      after_create(@location_release)
    else
      render :new
    end
  end

  private

  def set_project
    @project = @account.projects.find(params[:project_id])
  end

  def set_account
    @account = Account.find_by(slug: params[:account_id])
  end

  def set_contract_template
    @contract_template = @project.contract_templates.find(params[:contract_template_id])
  end

  def location_releases
    policy_scope(@project.location_releases)
  end

  def build_location_release(params = {})
    location_releases.build(params).tap do |location_release|
      authorize(location_release)
    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,
      :signature_base64,
      :locale, :contract_template, :filming_started_on, :filming_ended_on,
      :filming_hours,
      photos: []
    )
  end

  def location_release_params_with_locale
    location_release_params.merge(locale: I18n.locale)
  end

  def location_release_params_with_locale_and_contract_template
    location_release_params_with_locale.merge(contract_template: @contract_template)
  end

  def log_create_analytics
    TrackAnalyticsJob.perform_later(nil, nil, :track_create_native_release, release_type: LocationRelease.to_s, account: @account, user_agent: request.user_agent, user_ip: request.remote_ip)
  end
end
