//
//  SelectButton.m
//  JasonDevelop
//
//  Created by Jason Lee on 2013. 12. 16..
//  Copyright (c) jasondevelop. All rights reserved.
//

#import "CommonUtil.h"
#import "SelectButton.h"
#import "UIViewController-ActionSheetSimulation.h"

#define kfToolBarHeight 44.0f
#define kUIBtnTintColor [UIColor whiteColor]

@interface SelectButton () <UIPickerViewDataSource, UIPickerViewDelegate> {

@protected

    UIView *_simulatedActionSheetView;
    UIPickerView *_pickerView;
    UIToolbar *_actionToolbar;
    NSInteger _selectedRow;
}

@end

@implementation SelectButton

- (void)awakeFromNib {
    [super awakeFromNib];

    [self addTarget:self action:@selector(didTouchButton) forControlEvents:UIControlEventTouchUpInside];
}


- (id)selectedTitle {
    if (![[_dataDict allKeys] containsObject:[self titleForState:UIControlStateNormal]]) return nil;

    NSInteger row = [_pickerView selectedRowInComponent:0];
    return [_dataDict keyAtIndex:(NSInteger)row];
}

- (void)setSelectedTitle:(id)selectedTitle {

    NSString *selectedKey = nil;
    NSInteger row = 0;
    for (NSString *lKey in _dataDict.allKeys) {
        if ([selectedTitle isEqualToString:lKey]) {
            break;
        }
        row++;
    }

    if (row < _dataDict.allKeys.count) {
        [_pickerView selectRow:row inComponent:0 animated:YES];
        selectedKey = [_dataDict keyAtIndex:(NSInteger)row];
        [self setTitle:selectedKey forState:UIControlStateNormal];
    }
}

- (id)selectedValue {
    //플레이스 홀더일 경우, nil 리턴
    if (![_dataDict objectForKey:[self titleForState:UIControlStateNormal]]) return nil;

    NSInteger row = [_pickerView selectedRowInComponent:0];
    return [_dataDict objectAtIndex:(NSInteger)row];
}

- (void)setSelectedValue:(id)selectedValue {

    BOOL isValueStringType = [selectedValue isKindOfClass:[NSString class]]; //스트링이 아니면, NSNumber
    NSString *selectedKey = nil;
    NSInteger row = 0;
    for (NSObject *object in _dataDict.allValues) {
        if (isValueStringType) {
            NSString *value = (NSString *)object;
            if ([value isEqualToString:selectedValue]) {
                break;
            }
        } else {
            NSNumber *value = (NSNumber *)object;
            if ([value isEqualToNumber:selectedValue]) {
                break;
            }
        }
        row++;
    }

    if (row < _dataDict.allKeys.count) {
        [_pickerView selectRow:row inComponent:0 animated:YES];
        selectedKey = [_dataDict keyAtIndex:(NSInteger)row];
        [self setTitle:selectedKey forState:UIControlStateNormal];
    }
}

- (void)reloadDataDict {
    [_pickerView reloadAllComponents];
}

#pragma mark - UIActionSheet Delegate

- (void)didTouchButton {
    [self showPicker];
}

- (void)generateActionSheet {
    if (_pickerView)
        return;

    //피커뷰를 만듬.
    _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, 216)];
    _pickerView.dataSource = self;
    _pickerView.delegate = self;
    _pickerView.showsSelectionIndicator = YES;

    UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"취소" style:UIBarButtonItemStylePlain target:self action:@selector(pickerCancelPressed:)];

    UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    UIBarButtonItem *fixedSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
    fixedSpace.width = 10;
    UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithTitle:@"선택" style:UIBarButtonItemStylePlain target:self action:@selector(pickerDonePressed:)];

    if (IOS_VERSION >= 7.0f) {
        cancelButton.tintColor = kUIBtnTintColor;
        doneBtn.tintColor = kUIBtnTintColor;
    }

    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    _actionToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, width, kfToolBarHeight)];
    _actionToolbar.barStyle = UIBarStyleBlack;
    [_actionToolbar setItems:[NSArray arrayWithObjects:fixedSpace, cancelButton, flexSpace, doneBtn, fixedSpace, nil] animated:YES];


    _simulatedActionSheetView = [[CommonUtil currentViewController] actionSheetSimulationWithPickerView:_pickerView withToolbar:_actionToolbar];
}

- (void)showPicker {
    [[CommonUtil currentViewController].view endEditing:YES];
    
    if (!_simulatedActionSheetView) {
        [self generateActionSheet];
    }
    [[CommonUtil currentViewController] showActionSheetSimulation:_simulatedActionSheetView pickerView:_pickerView withToolbar:_actionToolbar];
}

- (void)pickerDonePressed:(id)sender {
    [[CommonUtil currentViewController] dismissActionSheetSimulation:_simulatedActionSheetView];

    if (!_dataDict || _dataDict.count <= 0)
        return;

    NSInteger row = [_pickerView selectedRowInComponent:0];
    NSString *key = [_dataDict keyAtIndex:(NSInteger)row];

    [self setTitle:key forState:UIControlStateNormal];
    [self setTitleColor:_textColorNormal forState:UIControlStateNormal];

    if ([_delegate respondsToSelector:@selector(didChangedSelectRow:selectedIndex:)]) {
        [_delegate didChangedSelectRow:self selectedIndex:row];
    }

    if ([_delegate respondsToSelector:@selector(didChangedSelect:info:)]) {
        NSDictionary *info = @{@"key": key,
                               @"value": [self.dataDict objectForKey:key]};

        [_delegate didChangedSelect:self info:info];
    }
}


- (void)pickerCancelPressed:(id)sender {
    [[CommonUtil currentViewController] dismissActionSheetSimulation:_simulatedActionSheetView];
}



#pragma mark - UIPickerViewDelegate

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return _dataDict.count;
}


- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    NSString *string = [_dataDict keyAtIndex:(NSInteger)row];
    return string;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
//    NSString *string = [_dataDict keyAtIndex:(NSInteger)row];
//    [self setTitle:string forState:UIControlStateNormal];
//    [self setTitleColor:_textColorNormal forState:UIControlStateNormal];
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {

    UILabel *text = (UILabel*)view;

    if (!text){
        text = [[UILabel alloc] init];
        //Set label style
        text.font = [UIFont systemFontOfSize:16.0f];
        text.textColor = [UIColor whiteColor];
        text.textAlignment = NSTextAlignmentCenter;
    }

    //Set text value
    text.text = [_dataDict keyAtIndex:row];

    return text;
}

@end


@interface SelectListButton () {

}
@end

@implementation SelectListButton

- (void)awakeFromNib {
    //부모클래스의 함수를 호출하지 않음.
    [self addTarget:self action:@selector(didTouchButton) forControlEvents:UIControlEventTouchUpInside];
}

@end


