#!/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()
    @form1 = AlForm.new(
      AlText.new( "text1" ),
      AlInteger.new( "integer1" ),

      AlSubmit.new( "submit1", :value=>"決定",
        :tag_attr=> {:style=>"float: right;"} )
    )

    @form2 = AlForm.new(
      AlText.new( "text2" ),
      AlText.new( "text3" ),

      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_init()
    @persist.create( {:text1=>"", :integer1=>"", :text2=>"", :text3=>"" } )
    Alone::redirect_to( Alone::make_uri() )
  end


  ##
  # 更新フォーム1
  #
  def action_edit1()
    @form = @form1
    @form.action = Alone::make_uri( :action=>"edit1_submit" )
    edit_common()
  end


  ##
  # 更新確定
  #
  def action_edit1_submit()
    @form = @form1
    @form.action = Alone::make_uri( :action=>"edit1_submit" )
    edit_submit_common()
  end



  ##
  # 更新フォーム2
  #
  def action_edit2()
    @form = @form2
    @form.action = Alone::make_uri( :action=>"edit2_submit" )
    edit_common()
  end


  ##
  # 更新確定
  #
  def action_edit2_submit()
    @form = @form2
    @form.action = Alone::make_uri( :action=>"edit2_submit" )
    edit_submit_common()
  end


  ##
  # 更新フォーム共通処理
  #
  def edit_common()
    @persist.read()
    @form.values = @persist.values

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


  ##
  # 更新確定共通処理
  #
  def edit_submit_common()
    if ! @form.validate()
      # バリデーションエラーならフォームへ戻す
      AlTemplate.run( @template_create || "#{AL_BASEDIR}/templates/form.rhtml" )
      return
    end

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

end
