#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/environment.rb'

def marek_internal_decrypt(mastr)
  tostr = ''
  offset = 0
  scan = true
  while scan
    if  offset >= mastr.length
      break
    end
    skipChars = mastr[offset..offset].to_i
    offset += skipChars + 1
    if  offset >= (mastr.length - 1)
      tostr = ''
      break
    end
    if mastr[offset..offset] == '0'
      if mastr[offset+1..offset+1].to_i < 5
        tostr << '/'
      else
        tostr << '@'
      end
    elsif mastr[offset..offset] == '1'
      if mastr[offset+1..offset+1].to_i < 5
        tostr << ' '
      else
        tostr << '.'
      end
    else
      tostr << mastr[offset+1..offset+1]
    end
    offset += 2
    scan = false if mastr[offset].nil?
  end
  tostr.tr('A-Za-z', 'N-ZA-Mn-za-m')
end

def marek_decrypt(inMSpicID,prov_strkey='')
  deStr = marek_internal_decrypt(inMSpicID)
  if deStr.empty?
    deStr = inMSpicID if (Integer(inMSpicID) rescue false)
  else
    if (Integer(deStr) rescue false)
      if (deStr.length <= 3) and not (prov_strkey == 'Cosmos')
        if (Integer(inMSpicID) rescue false)
          deStr = inMSpicID
        else
          deStr = ''
        end
      end
    else
      if (Integer(inMSpicID) rescue false)
        deStr = inMSpicID
      else
        deStr = ''
      end
    end
  end
  deStr
end

options = {}

OptionParser.new do |opts|
  opts.banner = "Usage: decrypt_ms_picture_id [options]"

  opts.on("-i", "--ms_pic_id [ms_picture_id]",String, "ms_picture_id") do |v|
    options[:ms_pic_id] = v
  end

  options[:str_key] = ''
  opts.on("-p", "--provider [string_key]",String, "ms_picture_id") do |v|
    options[:str_key] = v
  end

  opts.on_tail('-h', '--help', 'Show this message') do
    puts opts
    exit
  end

end.parse!

if options.blank?
  puts 'Error : no arguments, use -h or --help for help'
  exit
end

ms_pic_id_decrypt=marek_decrypt(options[:ms_pic_id],options[:str_key])
puts "ms_picture_id decrypted : #{ms_pic_id_decrypt}"