#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
#
# alone : web application framework for small embedded systems.
#               Copyright (c) 2009-2010 Inas Co Ltd. All Rights Reserved.
#
# This file is destributed under BSD License. Please read the COPYRIGHT file.
#

require 'al_form'
require 'al_template'
require 'al_persist_sh'

DB_FILE = "data/test.conf"


class AlController

  ##
  # constructor
  #
  def initialize()
    @form = AlForm.new(
      AlText.new( "key", :label=>"キー名", :required=>true ),
      AlText.new( "value", :label=>"値" ),
      AlSubmit.new( "submit1", :value=>"決定",
        :tag_attr=> {:style=>"float: right;"} )
    )
    @persist = AlPersistSh.connect( DB_FILE )
  end


  ##
  # デフォルトアクション
  #
  def action_index
    @persist.read()
    AlTemplate.run( "./list.rhtml" )
  end


  ##
  # 新規キー登録フォーム表示
  #
  def action_create()
    @form.action = Alone::make_uri( :action=>'create_submit' )
    AlTemplate.run( @template_create || "#{AL_BASEDIR}/templates/form.rhtml" )
  end


  ##
  # 新規キー登録確定
  #
  def action_create_submit()
    @form.action = Alone::make_uri( :action=>'create_submit' )

    if ! @form.validate()
      # バリデーションエラーならフォームへ戻す
      AlTemplate.run( @template_create || "#{AL_BASEDIR}/templates/form.rhtml" )
      return
    end

    @result = @persist.create( { @form.values[:key] => @form.values[:value] } )
    AlTemplate.run( @template_create_submit || "#{AL_BASEDIR}/templates/form_submit.rhtml" )
  end


  ##
  # 更新 フォーム表示
  #
  def action_update()
    raise "Primary key is not given."  if ! @form.validate( :key )
    @form.action = Alone::make_uri( :action=>'update_submit' )

    @persist.read()
    @form.widgets[:value].set_value( @persist[ @form.values[:key] ] )
    @form.widgets[:key].set_attr( :readonly=>'readonly' )

    AlTemplate.run( @template_update || "#{AL_BASEDIR}/templates/form.rhtml" )
  end
    

  ##
  # 更新 確定
  #
  def action_update_submit()
    @form.action = Alone::make_uri( :action=>'update_submit' )

    if ! @form.validate()
      # バリデーションエラーならフォームへ戻す
      AlTemplate.run( @template_update || "#{AL_BASEDIR}/templates/form.rhtml" )
      return
    end

    @result = @persist.update( { @form.values[:key] => @form.values[:value] } )
    AlTemplate.run( @template_create_submit || "#{AL_BASEDIR}/templates/form_submit.rhtml" )
  end


  ##
  # 削除 確認画面表示
  #
  def action_delete()
    raise "Primary key is not given."  if ! @form.validate( :key )
    @form.action = Alone::make_uri( :action=>'update_submit' )

    @persist.read()
    @form.widgets[:value].set_value( @persist[ @form.values[:key] ] )

    AlTemplate.run( "./delete.rhtml" )
  end


  ##
  # 削除 確定
  #
  def action_delete_submit()
    raise "Primary key is not given."  if ! @form.validate( :key )

    @result = @persist.delete( { @form.values[:key] => @form.values[:value] } )
    AlTemplate.run( @template_delete_submit || "#{AL_BASEDIR}/templates/delete_submit.rhtml" )
  end

end
