//
//  DaysPopupView.m
//  kneet
//
//  Created by Jason Lee on 5/12/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "JDObject.h"
#import "CustomLabel.h"
#import "CustomCheckBox.h"

#import "DaysPopupView.h"
#import "UIDeviceUtil.h"
#import "ItemModel.h"



@interface DaysPopupView () {
    ItemSubModel *_subCondition;
}

@end

@implementation DaysPopupView
@synthesize condition = _condition;

- (id)initFromNib {

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

            //XIB의 경우, 현재 화면 사이즈로 맞춰줘야 함.
            self.frame = [UIScreen mainScreen].bounds;

            self.lblTitle.text = NSLocalizedString(@"이 요일에만 실행",nil);

            ((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;


            for (CustomCheckBox *chk in _chkDays) {
                [self alignTextAndImageOfButton:chk];
            }
            
            //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)didMoveToSuperview {

}


- (void)setDaysOfWeek:(NSString *)daysOfWeek {
    //dayOfWeek
    NSArray *days = [daysOfWeek componentsSeparatedByString:@","];
    for (NSString *d in days) {

        NSInteger idx = [_chkDays indexOfObjectPassingTest:^BOOL(CustomCheckBox *obj, NSUInteger idx, BOOL *stop) {
            return [d isEqualToString:obj.value];
        }];

        if (idx != NSNotFound) {
            CustomCheckBox *chk = _chkDays[idx];
            chk.checked = YES;
        }
    }
}

- (ItemModel *)condition {

    //validate
    if (![self validateCondition]) {
        return nil;
    }

    _subCondition.cmdclsValue = [self commandClassValue];
    _subCondition.daysOfWeek = [self daysOfWeek];

    return _condition;
}

- (void)setCondition:(ItemModel *)condition {
    _condition = condition;

    if (!_condition) {
        _condition = [[ItemModel alloc] init];
        _condition.itemName = NSLocalizedString(@"요일", @"요일");
        _condition.itemSubTypeCode = ksConditionSubTypeCodeDaysOfWeek;
    }

    if (_condition.subItems && _condition.subItems.count) {
        _subCondition = _condition.subItems[0];
    } else {
        _subCondition = [[ItemSubModel alloc] init];
        _subCondition.conditionTypeCode = @"09";
        _condition.subItems = (NSMutableArray<ItemSubModel> *)[[NSMutableArray alloc] initWithObjects:_subCondition, nil];
    }

    [self setDaysOfWeek:_subCondition.cmdclsValue];
}

- (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 {
    //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, [self stringOfDay:i]];
        }
        i++;
    }
    return days;
}

- (NSString *)commandClassValue {
    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 {

    //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)btnConfirmTouched:(id)sender {

    //validate
    if (![self validateCondition]) {
        return;
    }

    [super btnConfirmTouched:sender];
}

@end
