//
//  TypePickerView.m
//  ZipperGym
//
//  Created by JianjiYuan on 15-4-2.
//  Copyright (c) 2015年 JianjiYuan. All rights reserved.
//

#import "TypePickerView.h"

@implementation TypePickerView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
    }
    return self;
}

- (void)setTitles:(NSArray *)titles
{
    if (_titles != titles) {
        _titles = nil;
        _titles = [titles copy];
    }
    
    [self initComponents];
    
}

- (void)initComponents
{
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    int itemCount = (int)_titles.count;
    
    CGFloat viewWidth = CGRectGetWidth(self.frame);
    CGFloat viewHeight = CGRectGetHeight(self.frame);
    CGFloat itemWidth = (viewWidth-(1+itemCount)*self.columnMargin)/itemCount;
    CGFloat itemHeight = (viewHeight-(self.topMargin + self.bottomMargin));
    
    CGRect itemRect = CGRectMake(0, 0, itemWidth, itemHeight);
    for (int i = 0; i<itemCount; i++) {
        itemRect.origin.x = self.columnMargin+(itemWidth+self.columnMargin)*i;
        itemRect.origin.y = self.topMargin;
        
        UIButton *btnItem = [UIButton buttonWithType:UIButtonTypeCustom];
        [btnItem setTitle:_titles[i] forState:UIControlStateNormal];
        btnItem.tag = 100+i;
        [btnItem setFrame:itemRect];
        [btnItem addTarget:self action:@selector(btnItemClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:btnItem];
        
        if (i == 0) {
            btnItem.selected = YES;
        }
    }
}

- (void)btnItemClick:(UIButton *)sender
{
    for (UIView *subView in self.subviews) {
        if ([subView isKindOfClass:[UIButton class]]) {
            [((UIButton *)subView) setSelected:NO];
        }
    }
    sender.selected = YES;
    
    if (self.typePickerClick) {
        self.typePickerClick((int)sender.tag-100);
    }
}

- (UIButton *)buttonAtIndex:(int)index
{
    UIView *subView = [self viewWithTag:100+index];
    if ([subView isKindOfClass:[UIButton class]]) {
        return (UIButton *)subView;
    }
    return nil;
}


@end
