class StatusesController < ApplicationController
  before_action :users_only, except: [:index, :show, :timeline]
  before_action :set_status, only: [:show, :edit, :update, :destroy]
  before_action :set_user, except: [:timeline]
  before_action :check_ownership, only: [:edit, :update, :destroy]

  
  def redirect_to_current_user
    if current_user
      redirect_to user_status_path(current_user)
    else
      redirect_to new_user_session_path, alert: "Please log in to view statuses."
    end
  end
  def check_ownership
  unless @status && @status.user == current_user
    redirect_to user_status_path(@user || current_user), alert: "You don't have permission to do that silly!"
  end
end

  def edit
  @user = current_user
  end

  def update
    @user = current_user
    if @status.update(status_params)
      redirect_to user_status_path(@user, @status), notice: "Status updated!"
    else
      render :edit
    end
  end

  def show
  end
  def destroy
    @status.destroy
    redirect_to user_statuses_path(@user), notice: "Status deleted."
  end

  def redirect_to_current_user_new
    if current_user
      redirect_to new_user_status_path(current_user)
    else
      redirect_to new_user_session_path, alert: "Please log in to create a status."
    end
  end
  def index
  if params[:user_id].present?
    @user = User.find_by(id: params[:user_id]) || User.find_by(login: params[:user_id])
   end
   if @user
    @statuses = @user.statuses.order(created_at: :desc)
  else
    @statuses = []
 end
end
  def new
    if @user != current_user
       redirect_to user_statuses_path(current_user, @status), alert: "You can't do that silly!"
       return
    end
   @status = current_user.statuses.new
end  
  def create
    if @user != current_user
       redirect_to user_status_path(current_user), alert: "You can't do that silly!"
       return
    end
    @status = current_user.statuses.new(status_params)
    if @status.save
      redirect_to user_statuses_path(current_user, @status), notice: "Status created!"
    else
      render :new
    end
  end
  def timeline
    @statuses = Status.includes(:user, :icon_attachment)
                      .order(created_at: :desc).limit(30)
  end
  private

def set_status
  return unless params[:id].present?
  
  @status = Status.find_by(id: params[:id])
  unless @status
    redirect_to user_statuses_path(current_user), alert: "Status not found."
    return
  end

  @user = @status.user
end

def set_user
  return if @user.present?
  @user = if params[:user_id].present?
            User.find_by(id: params[:user_id]) || User.find_by(login: params[:user_id])
          else
            current_user
          end

  unless @user
    redirect_to root_path, alert: "User not found."
  end
end

def status_params
  params.require(:status).permit(:icon, :text, :mood, :music)
  end
end
