class WatchersController < ApplicationController
  before_action :require_login, except: %i[index]
  before_action :require_profile_completed, only: [:follow]
  # before_action :find_project_with_id
  before_action :get_target

  def index
    start_at = params[:start_at]
    end_at = params[:end_at]
    scope = @target.watchers.includes(:user)
    scope = scope.where("watchers.created_at > ? and watchers.created_at < ?", Time.at(start_at.to_i), Time.at(end_at.to_i)) if start_at.present? && end_at.present?
    @watchers = paginate(scope)
  end

  def unfollow
    begin
      return normal_status(2, "你还没有关注哦") unless current_user.watched?(@target)
      current_user.unwatch!(@target)
      render_ok({watchers_count: @target.watchers_count, watched: false})
    rescue Exception => e
      uid_logger_error(e.message)
      tip_exception(e.message)
      raise ActiveRecord::Rollback
    end
  end

  def follow
    begin
      return normal_status(2, "你已关注了") if current_user.watched?(@target)
      watcher = current_user.watch!(@target)
      watcher.ext_info = params[:ext_info]
      watcher.save
      if @target.is_a?(Project)
        ProjectActions::StarEvent.build(@target, current_user)
      end
      current_user.watch!(@target)
      render_ok({watchers_count: @target.watchers_count, watched: true})
    rescue Exception => e
      uid_logger_error(e.message)
      tip_exception(e.message)
      raise ActiveRecord::Rollback
    end
  end

  def check_watch
    is_watch = current_user.watched?(@target)
    render_result(is_watch ? 1 : 0)
  rescue Exception => e
    uid_logger_error(e.message)
    tip_exception(e.message)
  end

  private 

  def get_target 
    target_type = params[:target_type].to_s
    case  target_type 
    when "project" 
      @target = target_type.capitalize.constantize.find_by(id: params[:id])
    when "competition_info"
      @target = CompetitionInfo.where(:identifier => params[:id]).exists? ? CompetitionInfo.find_by(:identifier => params[:id]) : CompetitionInfo.find_by(id: params[:id])
    when "platform_communicate"
      @target = PlatformCommunicate.find_by(id: params[:id])
    else
      @target = target_type.capitalize.constantize.find_by(login: params[:id])   #用户
    end

    unless @target.present?
      normal_status(-1, "目标不存在")
    end

  end

end
