%w(rubygems camping sequel logger).each { |lib| require lib }

# http://code.google.com/p/ruby-sequel/wiki/CheatSheet
Camping.goes :SequelBlog

# this needs to be toggled at times, it is not sequel related !
# 2007-12-19 <codahale> : This is a bug in ruby2ruby which will be fixed in its next release (or so I hear).
=begin
require 'ruby2ruby'
class NilClass
   undef method_missing
end
=end

module SequelBlog
    # called by camping on start
    # do our connect to db and define our model
    #db = ::Sequel.sqlite '', :logger => Logger.new($stdout)  
    db = ::Sequel.sqlite 'sb.db', :logger => Logger.new($stdout)
    
    class Entry < Sequel::Model(:entry)
      set_schema do
        primary_key :id
        varchar     :title
        varchar     :body
        integer     :reads
      end
    end
    
    def self.create
      #Entry.create_table! # drop if exist then create
      Entry.create_table unless Entry.table_exists?
      #Entry.create(:title => 'Shoes', :body => 'body')
    end
end

#module Camping::Models
 # AR is locking this position becouse of design 
#end

module SequelBlog::Controllers
  
    class Index < R '/'
      def get
        #@page = Entry.paginate(1, 5) # first page, 5 rows per page
        #@entries = @page.all #use in view to nav #=> #@entries.next_page #@entries.prev_page
        
        @entries = Entry.limit(5) #Entry.all #Entry.filter(:title => 'Shoes') 
        render :list
      end
    end

    class Add
      def get
      end
      
      def post
        # create_with_params uses the params that corresponds to the table
        Entry.create_with_params input 
        
        #e = Entry.new
        #e.title = input.title
        #e.body  = input.body
        #e.save

        redirect Index
      end
    end
    
end

module SequelBlog::Views

    def layout
      html do
        head do
          title "SequelBlog"
        end
        body do
          h2 "SequelBlog"
          self << yield
        end
      end
    end

    def list

      for entry in @entries
        div entry.id, " ", entry.title, " ", entry.body, " ", entry.reads
      end
      
      p " - - "
      
      form :action => R(Add), :method => 'post' do
        label 'Title', :for => 'title'; br
        input :name => 'title', :type => 'text'; br
        
        label 'Body', :for => 'body'; br
        textarea :name => 'body'; br
        
        input :type => 'submit', :name => 'Send', :value => 'submit'
      end
    end

end

=begin
Run the example
camping sequelblog.rb
=end