class ThemesController < ApplicationController
  load_and_authorize_resource
  skip_load_resource :index

  def index
    @themes = Theme.where(disabled: false).order(id: :desc)
    if params[:q].present?
      @themes = @themes.where('name LIKE :q OR author LIKE :q OR short_desc LIKE :q', q: "%#{params[:q]}%")
    end
    @themes = @themes.page(params[:page])
    if request.format == "json"
      @themes = @themes.per(5)
    end
    respond_with(@themes)
  end

  def show
    respond_with(@theme)
  end

  def new
    @draft_key = params.require(:draft_key)
    @draft = Draft.find_by!(key: @draft_key) # Check draft existance
    respond_with(@theme)
  end

  def edit
  end

  def create
    @theme.user_id = current_user.try(:id)
    if @theme.save && theme_params[:draft_key].present?
      Draft.where(key: theme_params[:draft_key]).destroy_all
    end
    respond_with(@theme)
  end

  def update
    @theme.update(theme_params)
    respond_with(@theme)
  end

  def destroy
    @theme.destroy
    respond_with(@theme)
  end

  def orig
    @theme.allow_orig_dl? or raise_error_404
    DlLogEntry.create! theme_id: @theme.id, ident: request.user_agent.to_s[0..255],
                       ip_hash: gen_ip_hash, dl_target: :orig
    send_file @theme.orig_archive.path, filename: "#{@theme.name}_original.zip"
  end

  def archive
    DlLogEntry.create! theme_id: @theme.id, ident: request.user_agent.to_s[0..255],
                       ip_hash: gen_ip_hash, dl_target: :theme
    send_file @theme.theme_archive.path, filename: "theme-#{@theme.id}.zip"
  end

  private
  def set_theme
    @theme = Theme.find(params[:id])
  end

  def theme_params
    params.require(:theme).permit(:name, :short_desc, :author, :url, :allow_orig_dl, :draft_key, :license_cc, :license_pcl, :license_yukari, :license_other, :license_other_url)
  end
end
