//
//  DurationPopupView.m
//  kneet2
//
//  Created by Jason Lee on 1/25/16.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "JDObject.h"

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

#import "DurationPopupView.h"
#import "DatePickerButton.h"
#import "CustomTextField.h"

@interface DurationPopupView ()<UITextFieldDelegate> {
    
}

@end

@implementation DurationPopupView

- (id)initFromNib {
    
    for (UIView *view in [CommonUtil nibViews:@"DurationPopupView"]) {
        if ([view isKindOfClass:[DurationPopupView class]]) {
            self = (DurationPopupView *)view;
            
            //XIB의 경우, 현재 화면 사이즈로 맞춰줘야 함.
            self.frame = [UIScreen mainScreen].bounds;
            
            
            NSDate *date = [NSDate new];
            
            _tfStartYear.placeholder = _tfEndYear.placeholder = [NSString stringWithFormat:@"%ld", date.year];
            _tfStartMonth.placeholder = _tfEndMonth.placeholder = [NSString stringWithFormat:@"%ld", date.month];
            _tfStartDay.placeholder = _tfEndDay.placeholder = [NSString stringWithFormat:@"%ld", date.day];
            
            [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)didMoveToSuperview {
    
}

- (void)setCondition:(ItemModel *)condition {
    _condition = condition;
    
    if (_condition.itemSubTypeCode && [_condition.itemSubTypeCode isEqualToString:ksConditionSubTypeCodeDueDate]) {
        
        //        ItemSubModel *subCondition = _condition.subItems && _condition.subItems.count ? _condition.subItems[0] : nil;
        //        if (subCondition) {
        //            //set values.
        //            NSArray *darray = [subCondition.cmdclsValueMsg componentsSeparatedByString:@"~"];
        //
        //            //from
        //            [_btnFrom setTitle:darray[0] forState:UIControlStateNormal];
        //            if (darray.count > 1) {//to
        //                [_btnTo setTitle:darray[1] forState:UIControlStateNormal];
        //            }
        //        }
        
    } else {
        _condition.itemName = @"이 기간동안만";
        _condition.itemSubTypeCode = ksConditionSubTypeCodeDueDate;
    }
}


#pragma mark - textfiled delegate
- (void)moveToNextField:(id)sender {
    
    UITextField *tf = sender;
    
    UITextField *nextTf = [self viewWithTag:tf.tag + 1];
    
    [nextTf becomeFirstResponder];
    
    
}

- (void)moveToPrevField:(id)sender {
    
    UITextField *tf = sender;
    
    UITextField *nextTf = [self viewWithTag:tf.tag - 1];
    
    [nextTf becomeFirstResponder];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    BOOL isYear = textField.tag == 1 || textField.tag == 4;
    BOOL isMonth = textField.tag == 2 || textField.tag == 5;
    BOOL isDay = textField.tag == 3 || textField.tag == 6;
    
    //4자리 입력
    if (isYear && text.length > 4) {
        
        return NO;
    }
    else if(isMonth && [text integerValue] > 12) {
        
        textField.text = @"12" ;
        return NO;
    }
    else if(isDay && [text integerValue] > 31) {
        
        textField.text = @"31" ;
        return NO;
    }
    else if(!isYear && text.length > 2) {
        
        return NO;
    }
    
    return YES;
}

//custom textfiled auto scroll
- (void)textFieldDidBeginEditing:(UITextField *)textField {

    [textField becomeFirstResponder];
}



- (BOOL)validateDate{
    
    NSDate *today = [NSDate new];
    NSString *todayStr = [NSString stringWithFormat:@"%04ld%02ld%02ld", today.year, today.month, today.day];
    
    BOOL check = YES;
    
    
    NSString *start = [NSString stringWithFormat:@"%04ld%02ld%02ld",
                       [_tfStartYear.text integerValue],
                       [_tfStartMonth.text integerValue],
                       [_tfStartDay.text integerValue]];
    
    NSString *end = [NSString stringWithFormat:@"%04ld%02ld%02ld",
                     [_tfEndYear.text integerValue],
                     [_tfEndMonth.text integerValue],
                     [_tfEndDay.text integerValue]];
    
    if ([todayStr integerValue] > [start integerValue]) check = NO;
    if ([todayStr integerValue] > [end integerValue]) check = NO;
    
    
    NSLog(@"check : %d", check);
    NSLog(@"%ld %ld", [todayStr integerValue], [start integerValue]);
    
    if (!check) [[JDFacade facade] alert:@"기간을 다시 확인하세요."];
    
    
    return check;
}



#pragma mark - UI Events

- (IBAction)btnConfirmTouched:(id)sender {
    //validate
    
    ItemSubModel *subCondition = nil;
    
    if (_condition.subItems && _condition.subItems.count) {
        subCondition = _condition.subItems[0];
    } else {
        subCondition = [[ItemSubModel alloc] init];
        
        _condition.subItems = (NSMutableArray<ItemSubModel> *)[[NSMutableArray alloc] init];
        [_condition.subItems addObject:subCondition];
    }
    
    NSString *start = [NSString stringWithFormat:@"%04ld%02ld%02ld",
                       [_tfStartYear.text integerValue],
                       [_tfStartMonth.text integerValue],
                       [_tfStartDay.text integerValue]];
    
    NSString *end = [NSString stringWithFormat:@"%04ld%02ld%02ld",
                     [_tfEndYear.text integerValue],
                     [_tfEndMonth.text integerValue],
                     [_tfEndDay.text integerValue]];
    
    if (![self validateDate])
        return;
    
    
    //    subCondition.sourceId = @"VAR";
    subCondition.conditionTypeCode = @"09";
    subCondition.cmdclsValue = [NSString stringWithFormat:@"%@~%@", start, end];
    subCondition.cmdclsValueMsg = [NSString stringWithFormat:@"%@ ~ %@", start, end];
    
    
    [super btnConfirmTouched:sender];
}

@end
