#!/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_persist_sqlite'
AlRdbw.connect( "data/books.db" )

class Book < AlPersistSqlite

  CATEGORY_LIST = {0=>"一般",1=>"教養",2=>"実用",3=>"専門",5=>"婦人",
                   6=>"学参I（小中）",7=>"学参II（高校）",8=>"児童",9=>"雑誌"}

  ##
  # constructor
  #
  def initialize()
    super( AlRdbw.connect(), 'books', 'book_id' )   # tableもkeyも自分(モデル)が知っている
  end


  ##
  # create
  #
  def create( values = nil )
    @values = values if values
    @values[:create_date] = Time.now    # 作成日を追加する
    super()
  end


  ##
  # update
  #
  def update( values = nil )
    @values = values if values
    @values.delete(:create_date)        # 作成日は更新しない
    super()
  end


  ##
  # テーブル作成
  #
  def create_table()
    @persist_base.execute( "create table books ( book_id integer primary key, book_title text not null, writer text, publisher text, category integer, create_date date );" )
  end


  ##
  # 統計
  #
  def statistics( kind_of )
    case kind_of
    # 著者ベスト10
    when "writer"
      return @persist_base.select( "select writer,count(*) as count from books group by writer order by count(*) desc limit 10;" )
      
    # 出版社ベスト10
    when "publisher"
      return @persist_base.select( "select publisher,count(*) as count from books group by publisher order by count(*) desc limit 10;" )

    # カテゴリー
    when "category"
      rows = @persist_base.select( "select category,count(*) as count from books group by category order by count(*) desc limit 10;" )
      rows.each { |d| d[:category] = CATEGORY_LIST[ d[:category] ] }
      return rows
    end

    return nil
  end
end
