#coding=utf-8

module Mobile
  module Apis
    class Praise< Grape::API
      include ApiHelper
      resources :praise do
        desc "praise an activity"

        params do
          requires :type, type: String
          requires :openid, type: String
        end
        post ':id' do
          obj_id = params[:id]
          obj_type = params[:type]
          user = UserWechat.find_by_openid(params[:openid]).user
          pts = PraiseTread.where("praise_tread_object_id=? and praise_tread_object_type=? and user_id=?",obj_id,obj_type.to_s,user.id).first
          if pts.blank?
            praise_or_cancel(obj_type,obj_id,user,1)
            obj = PraiseTreadCache.where("object_id=? and object_type=?",obj_id,obj_type.to_s).first
            num = get_activity_praise_num(obj) if !obj.blank?
          else
            pts.destroy if !pts.blank?
            #再更新praise_tread_cache表 使相应的记录减1 当为0时删除
            ptc = PraiseTreadCache.where("object_id=? and object_type=?",obj_id,obj_type.to_s).first
            ptc.praise_minus(1) if !ptc.blank?
            if ptc.praise_num == 0
              ptc.delete
            end
            obj = PraiseTreadCache.where("object_id=? and object_type=?",obj_id,obj_type.to_s).first
            num = !obj.blank? ? get_activity_praise_num(obj) : 0
          end

          present :data, num
          present :status, 0
        end
      end
    end
  end
end