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

#import "ItemModel.h"

#import "CustomLabel.h"
#import "CustomButton.h"
#import "CustomCheckBox.h"
#import "CommonUtil.h"
#import "CustomTextField.h"
#import "TimePickerPopupView.h"

@implementation CustomTimePicker

- (void)awakeFromNib {
    self.layer.backgroundColor = [UIColor clearColor].CGColor;
}
- (void)addSubview:(UIView *)view {
    
    if (!_changed) {
        _changed = YES;
        [self setValue:kUITextColor02 forKey:@"textColor"];
    }
    [super addSubview:view];
}

@end

@interface TimePickerPopupView () <CustomTextFieldDelegate>{
    
}

@end

@implementation TimePickerPopupView

- (id)initFromNib {

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

            ((CustomCheckBox *)_chkDays[0]).value = ksDayOfWeekMON;
            ((CustomCheckBox *)_chkDays[1]).value = ksDayOfWeekTUE;
            ((CustomCheckBox *)_chkDays[2]).value = ksDayOfWeekWED;
            ((CustomCheckBox *)_chkDays[3]).value = ksDayOfWeekTHU;
            ((CustomCheckBox *)_chkDays[4]).value = ksDayOfWeekFRI;
            ((CustomCheckBox *)_chkDays[5]).value = ksDayOfWeekSAT;
            ((CustomCheckBox *)_chkDays[6]).value = ksDayOfWeekSUN;
            
            [_chkDays[0] setDaySelectBgImage:1];
            [_chkDays[6] setDaySelectBgImage:3];
            
            for (int i = 1; i < 6; i++) {
                [_chkDays[i] setDaySelectBgImage:2];
            }
            _txtHour.delegate = self;
            _txtHour.keyboardType = UIKeyboardTypeNumberPad;
            _txtHour.returnKeyType = UIReturnKeyNext;
            
            _txtMinute.delegate = self;
            _txtMinute.keyboardType = UIKeyboardTypeNumberPad;
            _txtMinute.returnKeyType = UIReturnKeyDone;
            
            [self.imgTitleBar setImage:[UIImage imageNamed:@"img_popup_bg_head"]inset:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
            
            
            [self.btnConfirm setBackgroundImage:[UIImage imageNamed:@"img_popup_btn_right"] forState:UIControlStateNormal capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
            [self.btnConfirm setBackgroundImage:[UIImage imageNamed:@"img_popup_btn_right_press"] forState:UIControlStateHighlighted capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
            
            
            [self.btnCancel setBackgroundImage:[UIImage imageNamed:@"img_popup_btn_left"] forState:UIControlStateNormal capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
            [self.btnCancel setBackgroundImage:[UIImage imageNamed:@"img_popup_btn_left_press"] forState:UIControlStateHighlighted capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
            
            //Localization
            [self.btnConfirm setTitle:NSLocalizedString(@"확인", @"확인") forState:UIControlStateNormal];
            [self.btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
        }
    }

    return self;
}

//- (void)alignTextAndImageOfButton:(UIButton *)button {
//    // the space between the image and text
//    CGFloat spacing = 6.0;
//    float textMargin = 0;
//    
//    // get the size of the elements here for readability
//    CGSize  imageSize   = button.imageView.image.size;
//    CGSize  titleSize   = button.titleLabel.frame.size;
//    CGFloat totalHeight = (imageSize.height + titleSize.height + spacing);      // get the height they will take up as a unit
//    
//    // lower the text and push it left to center it
//    button.titleEdgeInsets = UIEdgeInsetsMake( 0.0, -imageSize.width +textMargin, - (totalHeight - titleSize.height), +textMargin );   // top, left, bottom, right
//    
//    // the text width might have changed (in case it was shortened before due to
//    // lack of space and isn't anymore now), so we get the frame size again
//    titleSize = button.titleLabel.bounds.size;
//    
//    button.imageEdgeInsets = UIEdgeInsetsMake(25, 0.0, 0.0, -titleSize.width );     // top, left, bottom, right
//}


- (void)setTimeTrigger:(ItemModel *)timeTrigger {
    
    _timeTrigger = timeTrigger;

    if (_timeTrigger.itemSubTypeCode && [_timeTrigger.itemSubTypeCode isEqualToString:ksItemSubTypeCodeTimer]) {//기존 데이터가 있을 경우,
        ItemSubModel *subItem = _timeTrigger.timers[0];
        
        NSLog(@"subItem : %@", subItem);
        
        NSDateComponents *ds = [CommonUtil dateComponents:[NSDate date] timezone:[NSTimeZone systemTimeZone]];
        ds.hour = [subItem.hour integerValue];
        ds.minute = [subItem.minute integerValue];

        _btnMorning.selected = [subItem.hour integerValue] < 12;
        _btnAfternoon.selected = !_btnMorning.selected;
        _txtHour.text = subItem.hour;
        _txtMinute.text = subItem.minute;
        
        for (NSInteger i = 0 ; i < WEEKDAYS.count ; i++) {
            
            if ([subItem.dayofweek containsString: [WEEKDAYS objectAtIndex:i]]) {
                
                CustomCheckBox *chk = [_chkDays objectAtIndex:i];
                chk.checked = YES;
            }
        }
        
//        _timePicker.date = [[NSCalendar currentCalendar] dateFromComponents:ds];

    } else {//is new
        
        _timeTrigger.itemName = @"이 시간마다";
        _timeTrigger.itemSubTypeCode = ksItemSubTypeCodeTimer;
        
        NSDateComponents *ds = [CommonUtil dateComponents:[NSDate date] timezone:[NSTimeZone systemTimeZone]];
        ds.hour = 9;
        ds.minute = 0;
//        _timePicker.date = [[NSCalendar currentCalendar] dateFromComponents:ds];
        
//        for (CustomCheckBox *chk in _chkDays) {
//            chk.checked = YES;
//        }
        
        _btnMorning.selected = YES;
    }
}

- (void)setRefConditions:(NSMutableArray<ItemModel> *)refConditions {
    
    _refConditions = refConditions;
    
    [TimePickerPopupView setRefConditions:_refConditions chkDays:_chkDays];
}

+ (void)setRefConditions:(NSMutableArray<ItemModel> *)refConditions chkDays:(NSArray *)chkDays {

    NSArray<ItemSubModel> *subConditions = (NSArray<ItemSubModel> *)[refConditions matchedArrayInSubArrays:@"subItems" predicateFormat:@"conditionTypeCode == %@", @"09"];
    
    ItemSubModel *daysCondition = subConditions.firstObject;
    NSArray *days = [daysCondition.cmdclsValue componentsSeparatedByString:@"," ];
    for (NSString *day in days) {
        for (CustomCheckBox *chk in chkDays) {
            if ([chk.value isEqualToString:day]) {
                chk.checked = YES;
                break;
            }
        } 
    }
}


- (void)didMoveToSuperview {
    

}

#pragma mark - textfield delegate
- (void)moveToPrevField:(id)sender {
    
    [_txtHour becomeFirstResponder];
    
}

- (void)moveToNextField:(id)sender {
    
    [_txtMinute becomeFirstResponder];
    
}


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];

    if ([textField isEqual:_txtHour] && [text integerValue] > 23) {

        textField.text = @"23";
        return NO;
    }
    else if ([textField isEqual:_txtMinute] && [text integerValue] > 60) {
        
        textField.text = @"60";
        return NO;
    }
    else if (text.length > 2) {
        
        return NO;
    }

    return YES;
}


#pragma mark - UI Events
- (IBAction)btnMorningTouched:(id)sender {
    [self.btnMorning setSelected:YES];
    [self.btnAfternoon setSelected:NO];
}
- (IBAction)btnAfternoonTouched:(id)sender {
    [self.btnMorning setSelected:NO];
    [self.btnAfternoon setSelected:YES];
}

- (IBAction)btnConfirmTouched:(id)sender {
    
    //validate
    if (![TimePickerPopupView validateCondition:_chkDays]) {
        return;
    }
    
    if ([_txtHour.text isEmptyString] || [_txtMinute.text isEmptyString]) {
        
        return;
    }

    ItemSubModel *subItem = nil;
    
    if (_timeTrigger.subItems && _timeTrigger.subItems.count) {
        
        subItem = _timeTrigger.subItems[0];
        
    }
    else {
        
        subItem = [[ItemSubModel alloc] init];

        
        subItem.hour = _txtHour.text;
        subItem.minute = _txtMinute.text;
        subItem.dayofweek = [TimePickerPopupView daysOfWeek:_chkDays];

        _timeTrigger.timers = (NSMutableArray<ItemSubModel> *)[[NSMutableArray alloc] init];
        [_timeTrigger.timers addObject:subItem];
    }


    //time
//    NSDateComponents *ds = [CommonUtil dateComponents:_timePicker.date timezone:[NSTimeZone systemTimeZone]];
//    
//    subItem.hour = [NSString stringWithFormat:@"%zd", ds.hour];
//    subItem.minute = ds.minute < 10 ? [NSString stringWithFormat:@"0%zd", ds.minute] : [NSString stringWithFormat:@"%zd", ds.minute];
    
    //set Days condition
//    [TimePickerPopupView setDaysCondition:_refConditions chkDays:_chkDays];
    
    [super btnConfirmTouched:sender];
}


#pragma mark - Class Methods
//+ (NSString *)stringOfDay:(NSInteger)index {
//    NSString *day = nil;
//    switch (index) {
//        case 0:
//            day = NSLocalizedString(@"월", @"월");
//            break;
//        case 1:
//            day = NSLocalizedString(@"화", @"화");
//            break;
//        case 2:
//            day = NSLocalizedString(@"수", @"수");
//            break;
//        case 3:
//            day = NSLocalizedString(@"목", @"목");
//            break;
//        case 4:
//            day = NSLocalizedString(@"금", @"금");
//            break;
//        case 5:
//            day = NSLocalizedString(@"토", @"토");
//            break;
//        case 6:
//            day = NSLocalizedString(@"일", @"일");
//            break;
//    }
//    return day;
//}


+ (NSString *)daysOfWeek:(NSArray *)chkDays {
    //dayOfWeek
    NSMutableString *days = [[NSMutableString alloc] init];

    NSInteger i = 0;
    for (CustomCheckBox *chk in chkDays) {
        if (chk.checked) {
            
            NSString *prefix = [days isEmptyString] ? ksEmptyString : @", ";
            [days appendFormat:@"%@%@", prefix, WEEKDAY(i)];
        }
        i++;
    }
    return days;
}

+ (NSString *)daysOfWeekValue:(NSArray *)chkDays {
    NSMutableString *days = [[NSMutableString alloc] init];
    
    for (CustomCheckBox *chk in chkDays) {
        if (chk.checked) {
            NSString *prefix = [days isEmptyString] ? ksEmptyString : @",";
            [days appendFormat:@"%@%@", prefix, chk.value];
        }
    }
    return days;
}

+ (BOOL)validateCondition:(NSArray *)chkDays {
    
    //1.validate
    NSInteger count = 0;
    for (CustomCheckBox *chk in chkDays) {
        if (chk.checked) {
            count++;
        }
    }
    
    //1. validate
    if (count == 0) {
        [[JDFacade facade] alert:NSLocalizedString(@"요일을 선택해주세요", @"요일을 선택해주세요")];
    }
    return count;
}


+ (void)setDaysCondition:(NSMutableArray<ItemModel> *)conditions chkDays:(NSArray *)chkDays{
    
    [conditions enumerateObjectsUsingBlock:^(ItemModel *pCondition, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([pCondition.itemSubTypeCode isEqualToString:ksConditionSubTypeCodeDaysOfWeek]) {
            [conditions removeObject:pCondition];
            *stop = YES;
        }
    }];
    
    //set condition
    ItemModel *condition = [[ItemModel alloc] init];
    condition.itemName = @"해당 요일에만";
    condition.itemSubTypeCode = ksConditionSubTypeCodeDaysOfWeek;
    
    [conditions addObject:condition];
    
    //set subitems
    condition.subItems = [(NSMutableArray<ItemSubModel> *)[NSMutableArray alloc] init];

    ItemSubModel *subCondition = [[ItemSubModel alloc] init];
    subCondition.conditionTypeCode = @"09";
    subCondition.cmdclsValue = [TimePickerPopupView daysOfWeekValue:chkDays];
    subCondition.dayofweek = [TimePickerPopupView daysOfWeek:chkDays];
    

    [condition.subItems addObject:subCondition];
}



@end
