class InfoRiskControlService < ApplicationService

  attr_reader :receiver, :remote_ip 
  attr_accessor :status, :message


  def initialize(receiver="", remote_ip="0.0.0.0")
    @receiver = receiver
    @remote_ip = remote_ip 
    @status = 1
    @message = ""
  end

  def call
    if receiver == ""
      remote_ip_minute_risk_control
      remote_ip_risk_control if @status == 1
    else  
      remote_ip_minute_risk_control
      remote_ip_risk_control if @status == 1
      minute_risk_control  
      day_risk_control if @status == 1
    end

    return @status, @message
  end

  private 
  def remote_ip_minute_risk_control 
    result = Rails.cache.read("InfoRiskControlService-RemoteIp-Minute-#{remote_ip}")
    if result.present? 
      @status = 0 
      @message = "您的请求过于频繁，请稍后再试"
    else 
      Rails.cache.write("InfoRiskControlService-RemoteIp-Minute-#{remote_ip}", 1, expires_in: 1.minute)
    end
  end 

  def remote_ip_risk_control 
    result = Rails.cache.read("InfoRiskControlService-RemoteIp-#{remote_ip}")
    if result.present? 
      if result.to_i > 20
        @status = 0 
        @message = "暂时无法请求，请稍后再试"
      else 
        Rails.cache.write("InfoRiskControlService-RemoteIp-#{remote_ip}", result.to_i + 1)
      end
    else 
      Rails.cache.write("InfoRiskControlService-RemoteIp-#{remote_ip}", 1, expires_in: 1.day)
    end
  end

  def minute_risk_control 
    result = Rails.cache.read("InfoRiskControlService-Minute-#{receiver}")
    if result.present?  
      @status = 0 
      @message = "您的请求过于频繁，请稍后再试" 
    else 
      Rails.cache.write("InfoRiskControlService-Minute-#{receiver}", 1, expires_in: 1.minute)
    end
  end

  def day_risk_control 
    result = Rails.cache.read("InfoRiskControlService-Day-#{receiver}")
    if result.present? 
      if result.to_i > 10
        @status = 0 
        @message = "您的请求过于频繁，请稍后再试"
      else 
        Rails.cache.write("InfoRiskControlService-Day-#{receiver}", result.to_i + 1)
      end
    else 
      Rails.cache.write("InfoRiskControlService-Day-#{receiver}", 1, expires_in: 1.days)
    end 
  end

end