########### # config5.ru #

require 'thin'

# simple redirect middleware for doing / => /ui5/index.html

module FiveApples

class Pie
  def initialize(app, options={})
    @app = app
    @redir = options[:redir] || {}
    @erb = options[:erb] || []
  end
  def call(env)
    if @redir.has_key?(pi = env['PATH_INFO'])
      destination  = "#{env['rack.url_scheme']}://#{env['HTTP_HOST']}#{@redir[pi]}"
      destination << "?#{qs}" unless (qs=env['QUERY_STRING']).empty?
      [301, {'Location' => destination}, ['See Ya!']]

# quick and dirty ERB templating

    elsif @erb.include?(pa = env['PATH_INFO'])
      path = "#{pa}.erb".del_prefix('/')
      [200, {}, [ ERB.new(File.read(path)).result(FiveA.get_binding) ] ]
    else
      @app.call(env)
    end
  end
end

end

fiveapples = Rack::OData::Builder.new do

use Rack::ODataCommonLogger if FiveA.log

use Rack::Cors do
  allow do
    origins 'localhost:9494', '127.0.0.1:9494'
    resource '*',
      methods: [:get, :post, :delete, :put, :patch, :options, :head],
      headers: :any
  end
end

# Serve either the TwoWay+$batch or the simple OneWay variant

ui5d = FiveA.ui5d
idxh = "/#{ui5d}/index.html"
cmpjs = "/#{ui5d}/Component.js"

redirects =  {'/'    => idxh, 
              '/ui5' => idxh,
              '/ui5/' => idxh}
redirects["/#{ui5d}"] = idxh if FiveA.one_way  
redirects["/#{ui5d}/"] = idxh if FiveA.one_way
if FiveA.one_way     
  redirects["/ui5/index.html"] = idxh            
else
  redirects["/ui5_1way/index.html"] = idxh 
end
# some user friendly redirects
# Note: We need this because serving / with /ui5/index.html content does not work
# as is produces follow-up javascript resource requests like "/Component.js"
# outside of ui5 directory and it gives NOT FOUND
# and also some minimal ERB templates handling

use FiveApples::Pie, redir: redirects, erb: [idxh, cmpjs]

# serve local openui5 runtime from one directory up (avoiding symlinks)
use Rack::Static,  :urls => ["/resources"], :root => "openui5-runtime-#{OpenUI5::VERSION}"

# serve the ui5 app from ui5 (or ui5_1way)
use Rack::Static,  :urls => ["/#{ui5d}"]

# Serve the OData (prefixed /odata )

run ODataFiveApples.new

end

Thin::Server.start('0.0.0.0', 9494, fiveapples)