#coding=utf-8

module Mobile
  require_relative 'middleware/error_handler'
  require_relative 'apis/auth'
  require_relative 'apis/users'
  require_relative 'apis/courses'
  require_relative 'apis/watches'
  require_relative 'apis/upgrade'
  require_relative 'apis/homeworks'
  require_relative 'apis/comments'
  require_relative 'apis/issues'
  require_relative 'apis/activities'
  require_relative 'apis/whomeworks'
  require_relative 'apis/newss'
  require_relative 'apis/journal_for_messages'
  require_relative 'apis/messages'
  require_relative 'apis/blog_comments'
  require_relative 'apis/new_comment'
  require_relative 'apis/praise'
  require_relative 'apis/resources'
  require_relative 'apis/syllabuses'
  require_relative 'apis/projects'

  class API < Grape::API
    version 'v1', using: :path
    format :json
    content_type :json, "application/json;charset=UTF-8"
    use ActionDispatch::Session::CookieStore
    use Middleware::ErrorHandler

    helpers do
      def logger
        API.logger
      end

      def authenticate!
        raise('Unauthorized. 用户认证失败.') unless current_user
      end

      def session
        env['rack.session']
      end

      def current_user
        openid = session[:wechat_openid]
        if openid
          uw = UserWechat.find_by_openid(openid)
          return uw.user if uw
        end

        token = ApiKey.where(access_token: params[:token]).first
        if token && !token.expired?
          return User.find(token.user_id)
        end

        nil
      end
    end

    mount Apis::Auth
    mount Apis::Users
    mount Apis::Courses
    mount Apis::Watches
    mount Apis::Upgrade
    mount Apis::Homeworks
    mount Apis::Comments
    mount Apis::Issues
    mount Apis::Activities
    mount Apis::Whomeworks
    mount Apis::Newss
    mount Apis::JournalForMessages
    mount Apis::Messages
    mount Apis::BlogComments
    mount Apis::NewComment
    mount Apis::Praise
    mount Apis::Resources
    mount Apis::Syllabuses
    mount Apis::Projects

    add_swagger_documentation ({api_version: 'v1', base_path: '/api'})  if Rails.env.development?

  end
end


