class Api::V1::Projects::DatasetsController < Api::V1::BaseController
  before_action :require_public_and_member_above, only: [:show]
  before_action :require_member_above, only: [:create, :update]
  before_action :find_dataset, only: [:update, :show]
  before_action :check_menu_authorize

  def create 
    ::Projects::Datasets::CreateForm.new(dataset_params).validate!
    return render_error('该项目下已存在数据集！') if @project.project_dataset.present?
    @project_dataset = ProjectDataset.new(dataset_params.merge!(project_id: @project.id))
    if @project_dataset.save! 
      render_ok
    else 
      render_error('创建数据集失败！')
    end
  rescue Exception => e
    uid_logger_error(e.message)
    tip_exception(e.message)
  end

  def update 
    ::Projects::Datasets::CreateForm.new(dataset_params).validate!
    @project_dataset.attributes = dataset_params
    if @project_dataset.save! 
      render_ok
    else
      render_error("更新数据集失败！")
    end
  rescue Exception => e
    uid_logger_error(e.message)
    tip_exception(e.message)
  end

  def show 
    @attachments = kaminari_paginate(@project_dataset.attachments.includes(:author))
  end

  private 
  def dataset_params 
    params.permit(:title, :description, :license_id, :paper_content)
  end

  def find_dataset 
    @project_dataset = @project.project_dataset 
    return render_not_found unless @project_dataset.present?
  end

  def check_menu_authorize
    return render_not_found unless @project.has_menu_permission("dataset")
  end
end