class ApiHdDownloadLink
  prepend SimpleCommand

  def initialize(args)
    #TODO: Implement Max Links limit ?
    @max_links = 50
    @args = args
    @output = {}
    # @output[:server_name] = @args[:server_name]
    # @output[:title_name] = @args[:title_name]
  end

  def call
    build_links(@args[:ids])
  end

  attr_reader :args

  private

  def add_time_expiration(num_of_days = 3)
    (Time.current + num_of_days.days).strftime("%Y%m%d%H%M")
  end

  # TODO: Implement max link limit
  def build_links(ids)
    @output[:links] = {}
    ids.each do |ms_id|
      @output[:links][ms_id] = marek_request_build(ms_id)
    end
    @output
  end

  def marek_request_build(ms_pic_id)
    params = []
    params << "pRi6cJMr"
    params << ms_pic_id
    params << args[:server_name]
    params << args[:remote_ip]
    params << args[:title_name]
    params << args[:login]
    params << add_time_expiration
    marek_crypt(params.join("@@@"))
  end

  def marek_crypt(mastr)
    tostr = ""
    mastr_to_crypted = mastr.tr("A-Za-z", "N-ZA-Mn-za-m")
    mastr_to_crypted.split("").each do |c|
      randnum = rand(2) + 1
      tostr += randnum.to_s
      randnum.times do
        dol = rand(54); nextdummy = (dol > 26) ? rand(9).to_s : (rand(26) + 64).chr
        tostr += nextdummy
      end
      if c == "/"
        tostr += "0" + rand(4).to_s
      elsif c == "@"
        tostr += "0" + (rand(4) + 5).to_s
      elsif c == " "
        tostr += "1" + rand(4).to_s
      elsif c == "."
        tostr += "1" + (rand(4) + 5).to_s
      else
        tostr += (rand(8) + 2).to_s + c
      end
    end
    tostr
  end
end
