#coding=utf-8

module Mobile
  module Apis
    class Syllabuses < Grape::API

      resources :syllabuses do
        desc "获取大纲列表"
        params do
          requires :token, type: String
        end
        get do
          authenticate!

          cs = SyllabusesService.new
          courses = cs.user_syllabus(current_user)
          present :data, courses, with: Mobile::Entities::Syllabus,user: current_user
          present :status, 0
        end

        desc "获取某个大纲"
        params do
          requires :token, type: String
        end
        get ':id' do
          authenticate!

          ss  = SyllabusesService.new

          sy = ::Syllabus.find(params[:id])

          result = {:title=>sy.title, :id=>sy.id , :user_id=>sy.user_id,:courses=>sy.courses.not_deleted}

          present :data, result, with: Mobile::Entities::Syllabus,user: current_user
          present :status, 0
        end

        desc "获取新建大纲的权限"
        params do
          requires :token, type: String
        end
        post 'auth' do
          authenticate!

          auth = 0

          if (current_user.user_extensions && current_user.user_extensions.identity == 0 && current_user.allowed_to?(:add_course, nil, :global => true))
            auth = 1
          end

          present :auth, auth
        end

        desc "新建大纲"
        params do
          requires :token, type: String
          requires :title, type: String, desc: '大纲标题'
          requires :courses, type: Array[String], desc: '课程名'
        end
        post do
          authenticate!

          ss  = SyllabusesService.new

          sy = ss.create(current_user, params[:title],
                         params[:courses].map{|c| {name: c} })

          if sy.new_record?
            {status:-1, message: '创建大纲失败' }
          else
            present :data, sy, with: Mobile::Entities::Syllabus,user: current_user
            present :status, 0
          end

        end

        desc '编辑大纲'
        params do
          requires :token, type: String
          requires :title, type: String, desc: '大纲标题'
          # requires :add_courses, type: Array[String], desc: '课程名'
          # requires :modify_courses, type: Array[Integer,String], desc: '课程名'
        end
        post ':id/edit' do

          authenticate!

          ss  = SyllabusesService.new

          #修改课程大纲
          status = ss.edit(current_user, params)

          if status == -1
            {status:status, message: '修改课程信息失败' }
          else
            present :status, status
          end
        end
      end

    end
  end
end