#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
#
# alone : web application framework for small embedded systems.
#               Copyright (c) 2009-2011 Inas Co Ltd. All Rights Reserved.
#
# This file is destributed under BSD License. Please read the COPYRIGHT file.
#
# 蔵書管理サンプルアプリケーション

require "al_form"
require "al_mif"
require "al_graph"
require "al_graph_pie"
require "./m_books"


class AlController

  ##
  # constructor
  #
  def initialize()
    @form = AlForm.new(
      AlInteger.new( "book_id", :label=>"ブックID", :foreign=>true, :hidden=>true ),
      AlText.new( "book_title", :label=>"書名", :required=>true ),
      AlText.new( "writer", :label=>"著者" ),
      AlText.new( "publisher", :label=>"出版社" ),
      AlOptions.new( "category", :label=>"カテゴリ", :options=>Book::CATEGORY_LIST ),
      AlDate.new( "create_date", :label=>"登録日", :hidden=>true ),
      AlSubmit.new( "submit1", :value=>"決定", :tag_attr=> {:style=>"float: right;"} )
    )

    @persist = Book.new                 # モデルオブジェクトの生成
    @template_list = "./list.rhtml"     # 表示テンプレートの指定
    @search_condition = { :limit=>5 }   # リスト表示行数指定
  end


  ##
  # デフォルトアクション
  #
  def action_index()
    begin
      action_list()

    rescue =>ex
      if ex.message =~ /^no such table/
        @persist.create_table()
        retry
      else
        raise ex
      end
    end
  end


  ##
  # 検索
  #
  def action_find()
    form_find = AlForm.new(
      AlText.new( "book_title", :filter=>"value.strip" ),
      AlText.new( "writer", :filter=>"value.strip" ),
      AlText.new( "publisher", :filter=>"value.strip" ),
    )

    if ! form_find.validate
      action_index()
      return
    end

    w = {}
    w["book_title like"] = "%#{form_find[:book_title]}%"  if form_find[:book_title] != ""
    w["writer like"] = "%#{form_find[:writer]}%"  if form_find[:writer] != ""
    w["publisher like"] = "%#{form_find[:publisher]}%"  if form_find[:publisher] != ""

    @search_condition[:where] = w
    @search_condition[:total_rows] = true       # 検索件数も取得する
    action_list()
  end


  ##
  # 統計 画面HTML出力
  #
  def action_statistics()
    AlTemplate.run( "statistics.rhtml" )
  end


  ##
  # 統計 グラフ出力
  #
  def action_graph()
    kind_of = AlForm.get_parameter( AlText.new( "kind_of" ) )

    result = @persist.statistics( kind_of )
    label = []
    ydata = []

    result.each do |d|
      label << d[ kind_of.to_sym ]
      ydata << d[ :count ]
    end

    case kind_of
    when "writer", "publisher"
      graph = AlGraph.new
      graph.set_margin( nil, 30, 80, nil )
      graph.add_data_bar( ydata )
      graph.x_axis.set_labels( label )
      graph.x_axis.at_labels[:rotate] = 40
      graph.y_axis.at_labels[:format] = '%d'
      graph.draw()

    when "category"
      graph = AlGraphPie.new
      graph.add_data( ydata, label )
      graph.draw()
    end
  end

end
