class UrlsController < ApplicationController

  skip_before_action :require_login, only: [:index, :show, :mini]

  def index
    @urls = Url.search(params[:search]).page(params[:page]).per_page(Url::URLS_PER_PAGE)
  end

  def show
    @url = Url.find(params[:id])
    gon.wait_time = ENV["JS_SCREENSHOT_WAIT_TIME"].to_i
    gon.exec_time = ENV["JS_SCREENSHOT_EXEC_TIME"].to_i
  end

  def new
    @url = current_user.urls.new
  end

  def create
    if current_user.allow_more_urls?
      @url = current_user.urls_find_or_create safe_params
      if @url.valid?
        Url.notify_pusher!
        @url.set_screenshot!
        redirect_to url_path(@url), notice: "URL created"
      else
        render "new"
      end
    else
      redirect_to edit_profile_path, alert: "Your price plan does not allow you to create more urls. Change your plan."
    end
  end

  def edit
    @url = current_user.urls.find(params[:id])
  end

  def update
    @url = current_user.urls.find(params[:id])
    if @url.update_attributes(safe_params)
      Url.pusher_update_latest
      @url.reset_screenshot_details!
      @url.set_screenshot!
      redirect_to url_path(@url), notice: "URL updated"
    else
      render "edit"
    end
  end

  def destroy
    @url = current_user.urls.find(params[:id])
    if @url.destroy
      Url.notify_pusher!
      redirect_to urls_path, notice: "URL deleted"
    else
      redirect_to urls_path, alert: "Can't delete the url"
    end
  end

  # Action to redirect the urlmini to the original url
  def mini
    mini = Url.where(mini: params[:mini]).take!
    redirect_to mini.original
  end


  private

  # Generate strong parameters for url
  def safe_params
    params[:url].permit(:original)
  end

end
