//
//  MultiLevelPopupView.m
//  kneet2
//
//  Created by Jason Lee on 12/7/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "JDObject.h"

#import "CustomLabel.h"
#import "CustomButton.h"

#import "MultiLevelPopupView.h"
#import "CustomRadioGroup.h"
#import "CommandClassControlView.h"

@implementation MultiLevelPickerView

- (void)awakeFromNib {
    self.layer.backgroundColor = [UIColor clearColor].CGColor;
    [self setValue:kUITextColor02 forKey:@"textColor"];
}

- (void)didMoveToSuperview {
//    if (!_changed) {
//        _changed = YES;
//    }
    
    self.showsSelectionIndicator = YES;
    self.subviews[1].backgroundColor = kUITextColor02;
    self.subviews[2].backgroundColor = kUITextColor02;
}

@end

@interface MultiLevelPopupView () <UIPickerViewDataSource, UIPickerViewDelegate> {
    
    NSMutableArray<ItemModel> *_checkedItems;
    NSMutableArray *_cmdclsValueArray;
}

@end

@implementation MultiLevelPopupView

- (id)initFromNib {

    for (UIView *view in [CommonUtil nibViews:@"MultiLevelPopupView"]) {
        if ([view isKindOfClass:[MultiLevelPopupView class]]) {
            self = (MultiLevelPopupView *)view;

            //XIB의 경우, 현재 화면 사이즈로 맞춰줘야 함.
            self.frame = [UIScreen mainScreen].bounds;
            
            _rgroup = [[CustomRadioGroup alloc] init];
            
            _rdoUp.value = ksConditionTypeCodeGreatOrEqual;
            _rdoDown.value = ksConditionTypeCodeLessOrEqual;

            [_rgroup addRadioButton:_rdoUp];
            [_rgroup addRadioButton:_rdoDown];
            
            
            _multiLevelPicker.dataSource = self;
            _multiLevelPicker.delegate = self;
            
            //Localization
            [self.btnConfirm setTitle:NSLocalizedString(@"확인", @"확인") forState:UIControlStateNormal];
            [self.btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
        }
    }

    return self;
}

- (void)didMoveToSuperview {

}

#pragma mark - Main Logic

- (void)setRefSubItem:(ItemSubModel *)refSubItem {
    _refSubItem = refSubItem;
    
    if ([_refSubItem.conditionTypeCode isEqualToString:ksConditionTypeCodeLessOrEqual]) {
        [_rgroup someRadioButtonTouched:_rdoDown];
    }
    
    if (!_cmdclsValueArray) {
        _cmdclsValueArray = [[NSMutableArray alloc] init];
        
        CGFloat min = [_refSubItem.controlMinValue floatValue];
        CGFloat max = [_refSubItem.controlMaxValue floatValue];
        CGFloat half = _refSubItem.cmdclsValue && ![_refSubItem.cmdclsValue isEmptyString] ?
                        [_refSubItem.cmdclsValue floatValue] : (max - min) / 2.0f;
        
        CGFloat i = min;
        NSInteger zindex = 0;
        BOOL isZeroSet = NO;
        
        while (i <= max) {
            if (i != half && !isZeroSet) {
                zindex++;
            } else if (i == half) {
                isZeroSet = YES;
            }
            
            //type change --
            NSString *cmclsValue = [CommandClassControlView cmdclsValueForType:_refSubItem.dataTypeCode value:i];
            [_cmdclsValueArray addObject:cmclsValue];
            
            i += [_refSubItem.controlStep floatValue];
        }

        [_multiLevelPicker selectRow:zindex inComponent:0 animated:NO];
    }
    
    _lblUnit.hidden = !(_refSubItem.unit && ![_refSubItem.unit isEmptyString]);
    if (!_lblUnit.hidden) {
        _lblUnit.text = _refSubItem.unit;
    }
}


- (NSString *)cmdclsValue {
    
    NSString *rvalue = [_cmdclsValueArray objectAtIndex:[_multiLevelPicker selectedRowInComponent:0]];
    return rvalue && ![rvalue isEmptyString] ? [CommandClassControlView cmdclsValueForType:_refSubItem.conditionTypeCode value:[rvalue floatValue]]
                                                                                          : ksEmptyString;
}

#pragma mark - Picker Delegate

// 필수 사용메소드 2개 : 이 작업을 하면 피커에 데이터가 들어간다.
// 피커를 사용하기 위해 반드시 사용되어야 할 필수 메소드이다.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

// 피커를 사용하기 위해 반드시 사용되어야 할 필수 메소드이다.
- (NSInteger)pickerView:(UIPickerView *) pickerView numberOfRowsInComponent : (NSInteger)component{
    return _cmdclsValueArray.count;
}

// 피커를 사용하기 위해 반드시 사용되어야 할 필수 델리게이트이다.
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow: (NSInteger)row forComponent: (NSInteger)component{
    return _cmdclsValueArray[row];
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 40.0f;
}

#pragma mark - UI Events

- (IBAction)btnConfirmTouched:(id)sender {
    //validate
    _refSubItem.cmdclsValue = [_cmdclsValueArray objectAtIndex:[_multiLevelPicker selectedRowInComponent:0]];
    _refSubItem.conditionTypeCode = _rgroup.valueForChecked;
    
    [super btnConfirmTouched:sender];
}

@end
