require 'rubygems'
require 'camping'
require 'camping/session'

Camping.goes :Proto

module Proto
  include Camping::Session
  
  module Models
    class Article < Base; end

    class BasicVersion < V 1.0
      def self.up
        create_table :proto_articles do |t|
          t.column :id,    :integer
          t.column :title, :string
          t.column :body,  :text
        end
      end
      def self.down
        drop_table :proto_articles
      end
    end
    class TimeStamped < V 1.1
      def self.up
        add_column :proto_articles, :created_at, :datetime
      end
      def self.down
        remove_column :proto_articles, :created_at
      end
    end
  end
  
  def self.create
    Camping::Models::Session.create_schema
    Models.create_schema
  end
    
  module Controllers
    class Index < R '/'
      def get
        @state[:count] = (@state[:count] || 0) + 1
        @count = @state[:count]
        @articles = Article.find(:all)
        render :index;
      end
    end

    class Add < R '/add'
      def get
        if @state[:login]
          render :add
        else
          redirect Login
        end
      end
      def post
        Article.create!(input) if @state[:login]        
        redirect Index
      end
    end
    
    class Login < R '/login'
      def get
        form :method => 'post' do
          label 'wachtwoord'
          input :type => 'password', :name => 'password'
          input :type => 'submit'
        end
      end
      def post
        if input.password == 'douwe dabbert'
          @state[:login] = true
          redirect Add
        else
          h1 'no passeran'
        end
      end
    end
  end
  
  module Views
    def layout
      html do
        head { title 'a proto-prototype' }
        body { self << yield }
      end
    end
    
    def index
      p "je bent al #{@count} keer op deze pagina geweest"
      a 'nieuw artikel', :href => R(Add)
      @articles.each do |article|
        h1 article.title
        p article.created_at
        p article.body
      end
    end
    
    def add
      form :method => 'POST' do
        input :type => 'text', :name => 'title'
        br
        textarea :name => 'body', :rows => 10
        input :type => 'submit'
      end
    end
  end
end
