class Admin::AssetsController < Admin::AdminController

  before_action :set_asset, only: %i[ edit update destroy ]

  helper_method :sorting_technique


   # GET /assets
  def index
    @assets = Asset.public_send(sorting_technique, params[:reverse].present?)
                   .simple_search(params[:q])
                   .page(params[:page] || 1)

    render (params[:screen_id] || params[:node_id]) ? 'explore' : 'index'
  end




  # GET /assets/1/edit
  def edit
  end

  # PATCH/PUT /assets/1 or /assets/1.json
  def update
    respond_to do |format|
      if @asset.update(asset_params)
        format.html { redirect_to edit_admin_asset_url(@asset), notice: t(:'assets.updated') }
      else
        format.html { render :edit, status: :unprocessable_entity }
      end
    end
  end


  def upload
    blob = ActiveStorage::Blob.find_signed(params[:signed_id])
    @asset = Asset.create(file: blob, title: blob.filename.base.gsub("_", " "))

    respond_to do |format|
      format.turbo_stream
    end
  end


  # DELETE /assets/1 or /assets/1.json
  def destroy
    @asset.destroy!

    respond_to do |format|

      format.html { redirect_to url_for(action: :index, format: :html), notice: t('assets.destroyed') }
      unless params[:redirect_to]
        format.turbo_stream { flash.now[:notice] = t('assets.destroyed') }
      end
    end
  end


private



  def sorting_technique
    params[:sort].presence_in(%w(by_filename by_last_modified)) || :by_filename
  end


  # Use callbacks to share common setup or constraints between actions.
  def set_asset
    @asset = Asset.find(params[:id])
  end


  # Only allow a list of trusted parameters through.
  def asset_params
    params.require(:asset).permit(
      :title
    )
  end

end
