# -*- encoding : utf-8 -*-
class ReturnHdController < ApplicationController

  require 'json'

  skip_before_action :login_required

  def create
    logger.info "*** #{params.inspect}"
    message = {}
    u = User.find_by_login('pat')
    img_id = params["id"]
    logger.info "++++ img = #{img_id}"
    im = Image.find(img_id)
    requ = marek_request_build(im.ms_picture_id, u)
    uri = URI("http://ftp.pixpalace.com/cgi-bin/download_pixpalace.zip")
    res = Net::HTTP.post_form(uri, 'from' => requ)
    tempfile = Tempfile.new("wb")
    tempfile.binmode
    tempfile.write(res.body)
    tempfile.rewind
    pict = "public/#{im.file_name}"
    File.open(pict, "wb"){ |f| f.write(tempfile.read) }
    tempfile.close
    tempfile.unlink
    Net::SCP.upload!("192.168.200.13", "support",
                     pict, "/var/www/wordpress/test_pp/#{im.file_name}",
                     :ssh => { :password => "aide7ogh" })

    message["result"] = im.file_name

    json_message = message.to_json
    respond_to do |format|
      format.json { render json: json_message }
    end
  end

  private

  def marek_request_build(ms_pic_id, user)
    params = []
    params << '9Pu0NkL41'
    params << ms_pic_id
    params << user.title.server.name
    params << request.remote_ip
    params << user.title.name
    params << user.login
    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
