class V1::CollectionsController < ApplicationController
  include ::SociableController
  include ::FollowableController
  include ::TaggableController
  include ::DeletedObjectsController
  include ::HighlightsController
  include ::Paginator


  before_action :set_collection, only: [:show, :update, :destroy, :add_object]
  before_action :authenticate_user!, only: [:create, :update, :destroy]

  # GET /v1/collections
  # GET /v1/collections.json
  def index
    collections = paginate Collection
    render json: collections
  end

  # GET /v1/collections/1
  # GET /v1/collections/1.json
  def show
    render json: @collection
  end

  # POST /v1/collection
  # POST /v1/collection.json
  def create
    collection = Collection.new(collection_params)
    

    if collection.save
      collection.add_items(items_params[:items])
      render json: collection, status: :created
    else
      render json: collection.errors, status: :unprocessable_entity
    end
  end

  # PUT/PATCH /v1/users/1
  # PUT/PATCH /v1/users/1.json
  def update

    if @collection.update(collection_params)
      @collection.add_items(items_params[:items])
      render json: @collection, status: :ok
    else
      render json: @collection.errors, status: :unprocessable_entity
    end
  end

  # DELETE /v1/collections/1
  # DELETE /v1/collections/1.json
  def destroy
    @collection.destroy
    render status: :ok
  end

  # POST /v1/collections/!/items
  def add_object
    render nothing: true, status: :unprocessable_entity if params.nil?
    @collection.add_items(items_params[:items])
    render json: @collection, status: :ok
  end

  private

  def deleted_resource; Collection; end
  def highlights_resource; Collection; end

  # social concerns methods
  def followable; set_collection; end
  def taggable; set_collection; end
  def sociable; set_collection; end

  def set_collection
    @collection ||= Collection.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def collection_params
    params.require(:collection).permit(:name, :description, :owner_id, :owner_type, :privacy, tags: [])
  end

  def items_params
    params.require(:collection).permit(items: [:type, :id, :order])
  end

end