
#==============================================================================#
# $Id: chart.rb,v 1.2 2004/01/23 00:38:04 yuya Exp $
# $Source: /cvsroot/gruby/gruby/lib/grb/chart/pie/chart.rb,v $
#==============================================================================#

require 'grb/chart/pie_base/chart'

#==============================================================================#

module GRb

  module Chart

    class PieChart < PieChartBase

      def initialize(property)
        super(property)
      end

      # FIXME: using GRb::Image
      def draw_sector(image, cx, cy, rx, ry, angle_start, angle_end, fill)
        s = (angle_start + 270) % 360
        e = (angle_end + 270)   % 360

        fill_color = image.set(fill)
        image.image.filledArc(cx, cy, rx * 2, ry * 2, s, e, fill_color, GD::Arc)

        if @property.edge.visible
          line_color = image.set(@property.edge.color)
          image.image.filledArc(cx, cy, rx * 2, ry * 2, s, e, line_color, GD::Arc | GD::NoFill | GD::Edged)
        end
      end
      protected :draw_sector

      def draw(image, box)
        dx, dy, rx, ry, cx, cy = self.calculate_box(box, @property.stretch)
        total = self.calculate_total(@values)
        ratio = self.calculate_ratio(@values, total)

        current = 0

        ratio.each { |item|
          angle_start  = current.ceil
          angle_end    = (current + item.ratio).ceil
          angle_median = ((angle_end - angle_start) / 2.0 + angle_start).ceil

          draw_sector(image, cx, cy, rx, ry, angle_start, angle_end, item.value.color)

          if @property.label.visible
            case @property.label.type
            when :name  then label = item.value.name
            when :value then label = item.value.value.to_s
            when :raito then label = format('%.01f%%', item.ratio / 360 * 100)
            else raise 'invalid label type'
            end

            self.draw_label(image, cx, cy, rx, ry, angle_median, label)
          end

          current += item.ratio
        }
      end

    end # PieChart

  end # Graph

end # GRb

#==============================================================================#
#==============================================================================#
