#import "CellBadge.h"
#import "Repository.h"
#import "PSMutex.h"

@implementation CellBadge

@synthesize value;

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.opaque = NO;
        self.userInteractionEnabled = NO;
    }else {
        [[PSMutex mainMutex] raiseMemoryError];
    }
    [[PSMutex mainMutex] showMemoryAlertIfError];
    return self;
}

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
	
    Repository* repo = [Repository mainRepository];
    
    NSString *countString = [NSString stringWithFormat:@"%d", value];
    CGSize numberSize = [countString sizeWithFont:repo.userFont];
    CGRect bounds = CGRectMake(4, 0, numberSize.width + 16 , 18);
    float radius = bounds.size.height / 2.0;
	
    UIColor *badgeColor = [UIColor colorWithRed:0.530 green:0.600 blue:0.738 alpha:1.000];
    CGContextSetFillColorWithColor(context, [badgeColor CGColor]);
    CGContextBeginPath(context);
    CGContextAddArc(context, (rect.size.width - bounds.size.width) + radius, radius, radius, M_PI / 2 , 3 * M_PI / 2, NO);
    CGContextAddArc(context, rect.size.width - radius, radius, radius, 3 * M_PI / 2, M_PI / 2, NO);
    CGContextClosePath(context);
    CGContextFillPath(context);
	
    [[UIColor whiteColor] set];
    bounds.origin.x = (rect.size.width - bounds.size.width) + (bounds.size.width - numberSize.width) / 2 + 1;
    [countString drawInRect:bounds withFont:repo.userFont];
}

@end
