class CentralServerExchangeApp < Sinatra::Base
  
  before do
    @site = Site.first
  end
  
  
  post "/site/set_registered" do
    begin
      private_key = OpenSSL::PKey::RSA.new(@site.private_key)
      roaming_id = private_key.private_decrypt(request.params['roaming_id'])
      @site.update_attributes(:roaming_id => roaming_id)
      body 'true'
    rescue
      body 'false'
    end
  end  
  
  get '/site/public_key' do
    begin
      if @site.public_key.nil?
        @site.generate_keys
        @site.save
      end
      body @site.public_key
    rescue
      body 'false'
    end
  end
  
  post '/purchase/:type' do
    begin
      private_key = OpenSSL::PKey::RSA.new(@site.private_key)

      case params[:type]
        when 'Design'
          purchase = PDesign.new.from_json(private_key.private_decrypt(request.params['purchase']))
        when 'ModuleApp'
          purchase = PModuleApp.new.from_json(private_key.private_decrypt(request.params['purchase']))
      end
      
      purchase.save
      body 'true'
    rescue
      body 'false'
    end
  end
  
end