
#import <math.h>
#import "PNChart.h"
#import "VankeSaleVolumeAPI.h"
#import "VankeBusinessChartCell_iPhone.h"

#define CHART_DIAMETER 200
#define COLOR_R 90
#define COLOR_G 60
#define COLOR_B 30

#pragma mark -

@implementation VankeBusinessChartCell_iPhone

PNPieChart *chartPieChart;

SUPPORT_AUTOMATIC_LAYOUT( YES )
SUPPORT_RESOURCE_LOADING( YES )

- (void)load
{
}

- (void)unload
{
    chartPieChart = nil;
}

- (BOOL)dataWillChange:(id)newData
{
    return self.data != newData;
}

- (void)dataDidChanged
{
    ChartValue *data = self.data;
    if (nil == data) {
        return;
    }
    
    $(self.lblChartTitle).DATA(data.name);
    $(self.lblChartTitle).ADD_CLASS(data.theme);
    if (nil != chartPieChart) {
        [chartPieChart updateChartData:[self getChartItems]];
    }
}

- (void)layoutDidFinish
{
    [self drawPieChart];
}

- (void) drawPieChart {
    chartPieChart = [[PNPieChart alloc] initWithFrame:CGRectMake((self.width - CHART_DIAMETER)/2.0 + 20, 0, CHART_DIAMETER, CHART_DIAMETER) items:[self getChartItems]];
    chartPieChart.descriptionTextColor = [UIColor blackColor];
    chartPieChart.descriptionTextFont  = [UIFont fontWithName:@"微软雅黑" size:12.0];
    chartPieChart.descriptionTextShadowColor = [UIColor clearColor];
    chartPieChart.showAbsoluteValues = NO;
    chartPieChart.showOnlyValues = YES;
    [chartPieChart strokeChart];
    [self.chartView addSubview:chartPieChart];
    
    //Build the legend
    chartPieChart.legendStyle = PNLegendItemStyleStacked;
//    chartPieChart.legendFont = 12.0;
    UIView *legend = [chartPieChart getLegendWithMaxWidth:200];
    
    //Move legend to the desired position and add to view
    [legend setFrame:CGRectMake(10, 0, legend.frame.size.width, legend.frame.size.height)];
    [self.chartView addSubview:legend];
}

-(NSArray*) getChartItems {
    ChartValue *data = self.data;
    for (NSInteger i = 0; i < [data.values count]; ++i) {
        PNPieChartDataItem *item = [data.values objectAtIndex:i];
        item.color = [self randomColor:i];
    }
    return data.values;
}

-(UIColor*) randomColor: (NSInteger) i {
    CGFloat r = ((COLOR_R * i + 20) % 255)  / 255.0;
    CGFloat g = ((COLOR_G * i + 180) % 255)  / 255.0;
    CGFloat b = ((COLOR_B * i + 35) % 255)  / 255.0;
    return [UIColor colorWithRed: r green:g blue:b alpha:1.0f];
}

@end


@implementation ChartValue

@synthesize theme = _theme;
@synthesize name = _name;
@synthesize values = _values;

@end
