
#  2010-06-06 katoy
#    $ shotgun naisen-sinatra.rb
#    acccess to "http://localhost:9393", "http://localhost:9393/list.json"
#
#  ruby 1.8.7

require 'rubygems'
require 'sinatra' # 1.0
require 'sinatra/jsonp' # 0.1.1
require 'erb'
# require 'json/pure'
require 'pp'

template :layout do
  s = <<EOS
<html lang="ja">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <head>
  <body>
    <hr>
      <%= yield %>
    <hr>
  </body>
</html>
EOS
end

helpers do
  def get_data_size
    100
  end

  def get_data(start = 0, limit = 100, sort = 'data_id', dir = 'ASC')

    # サンプルなので、DB などを使わずスクリプト中でデータを組み立ている。
    data = []
    for i in 1 .. 100 do
      data << {:data_id => i, :value => "#{1000 - i }"}
    end

    # ソート
    if (sort == 'data_id')
      data.sort!{|a, b| a[:data_id] <=> b[:data_id]} if dir == 'ASC'
      data.sort!{|a, b| b[:data_id] <=> a[:data_id]} if dir == 'DESC'
    elsif (sort == 'value')
      data.sort!{|a, b| a[:value] <=> b[:value]} if dir == 'ASC'
      data.sort!{|a, b| b[:value] <=> a[:value]} if dir == 'DESC'
    end

    # ページング
    first = start.to_i
    last = first + limit.to_i - 1
    ans = []
    for pos in first .. last do
      ans << data[pos]
    end
    ans
  end
end

#-- Top page
get '/' do
  redirect '/list'
end

# -- List
get '/list' do
  erb %{
   <div>
   <table style="border-style: solid;">
     <tr>
     <th>No.</th><th>ID</th><th>Value</th>
     </tr>
     <% count = 0 %>
     <% bgs = ['#FFFFFF', '#AAAAAA'] %>

     <% data = get_data %>
     <% count = 0 %>
     <% data.each do |row| %>
        <% count += 1 %>
        <tr bgcolor='<%= bgs[count % 2]%>'>
          <td align="right"><%= count %></td>
          <td align="right"><%= row[:data_id] %></td>
          <td><%= row[:value] %></td>
        </tr>
      <% end %>
   </table>
   </div>
  }
end

# -- List format json
get "/list.json" do

  # pp params
  start = params[:start]
  limit = params[:limit]
  sort = params[:sort]
  dir = params[:dir]

  data = get_data(start, limit, sort, dir)
  ans = {}
  ans[:totalCount] = get_data_size
  ans[:result] = data

  jsonp(ans, params[:callback])
end

#-- End of File ---
