//
//  RulesTriggerOptionViewController.m
//  kneet
//
//  Created by Jason Lee on 5/11/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "JDObject.h"
#import "ItemModel.h"

#import "DatePickerButton.h"
#import "TimePickerButton.h"
#import "CustomButton.h"
#import "CustomCheckBox.h"

#import "DaysPopupView.h"
#import "ModePopTableView.h"
#import "ExternHeatPopupView.h"

#import "RulesTriggerOptionViewController.h"

#define kfTriggerOptionTableViewCellHeight 60.0f

@interface RulesTriggerOptionViewController () {
    NSInteger _rowCount;
    UIImage *_imageBtnNormal, *_imageBtnDisable;

    DaysPopupView *_daysPopupView;
    ModePopTableView *_modePopTableView;
    ExternHeatPopupView *_externHeatPopView;
}
@end


#pragma mark - Class Definition

@implementation RulesTriggerOptionViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self initUI];
    [self prepareViewDidLoad];
}


- (void)initUI {
    self.tableView.scrollEnabled = NO;

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.separatorColor = kUILineColor2;
    self.tableView.backgroundColor = [UIColor clearColor];

    self.tableView.tableFooterView = [[UIView alloc] init]; //this call table events;

    CGRect sr = self.view.frame;
    sr.size.width = IPHONE_WIDTH;
    self.view.frame = sr;

    _imageBtnNormal = [UIImage imageNamed:@"tp_01_img_input_bg_02"];
    _imageBtnDisable = [UIImage imageNamed:@"tp_01_img_input_bg_02_disable"];

    _btnDueDateFrom.date = [NSDate date];
    _btnDueDateFrom.placeHolder = _btnDueDateFrom.dateString;
    [_btnDueDateTo setTitle:ksEmptyString forState:UIControlStateNormal];
//    _btnDueDateTo.date = [NSDate date];
//    _btnDueDateTo.placeHolder = _btnDueDateTo.dateString;

    [_btnDueTimeFrom setHour:9 minute:0];
    _btnDueTimeFrom.placeHolder = _btnDueTimeFrom.timeString;
    [_btnDueTimeTo setTitle:ksEmptyString forState:UIControlStateNormal];
//    [_btnDueTimeTo setHour:10 minute:0];
//    _btnDueTimeTo.placeHolder = _btnDueTimeTo.timeString;

    [_btnDueDateFrom setBackgroundImage:_imageBtnDisable forState:UIControlStateNormal];
    [_btnDueDateTo setBackgroundImage:_imageBtnDisable forState:UIControlStateNormal];
    [_btnDaysOfWeek setBackgroundImage:_imageBtnDisable forState:UIControlStateNormal];
    [_btnDueTimeFrom setBackgroundImage:_imageBtnDisable forState:UIControlStateNormal];
    [_btnDueTimeTo setBackgroundImage:_imageBtnDisable forState:UIControlStateNormal];
    [_btnModes setBackgroundImage:_imageBtnDisable forState:UIControlStateNormal];
    [_btnExternHeat setBackgroundImage:_imageBtnDisable forState:UIControlStateNormal];
    
    
    [_chkDueDate setTitle:NSLocalizedString(@"기간", @"기간") forState:UIControlStateNormal];
    [_chkDaysOfWeek setTitle:NSLocalizedString(@"요일", @"요일") forState:UIControlStateNormal];
    [_chkDueTime setTitle:NSLocalizedString(@"시간", @"시간") forState:UIControlStateNormal];
    [_chkModes setTitle:NSLocalizedString(@"홈 모드", @"홈 모드") forState:UIControlStateNormal];
    [_chkExternHeat setTitle:NSLocalizedString(@"지역온도", @"지역온도") forState:UIControlStateNormal];

//    _modes = (NSMutableArray<ModeModel> *)[[NSMutableArray alloc] init];
}

- (void)prepareViewDidLoad {

    ItemSubModel *subItem = nil;
    if ([_tmpItem.itemSubTypeCode isEqualToString:ksItemSubTypeCodeMode]) {//홈모드일 경우,
        _rowCount = 4;
        if (_tmpItem.modes && _tmpItem.modes.count) {
            subItem = _tmpItem.modes && _tmpItem.modes.count ? _tmpItem.modes[0] : nil;
        }
    } else if ([_tmpItem.itemSubTypeCode isEqualToString:ksItemSubTypeCodeTimer]) {//타이머일 경우,
        _rowCount = 4;
        if (_tmpItem.timers && _tmpItem.timers.count) {
            subItem = _tmpItem.timers && _tmpItem.timers.count ? _tmpItem.timers[0] : nil;
        }
    } else {
        if ([_tmpItem.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스일 경우,
            subItem = _tmpItem.predDevices && _tmpItem.predDevices.count ? _tmpItem.predDevices[0] : nil;
        } if ([_tmpItem.itemSubTypeCode isEqualToString:ksItemSubTypeCodeGeoFencing]) {//지오펜싱일 경우,
            subItem = _tmpItem.mobileDevices && _tmpItem.mobileDevices.count ? _tmpItem.mobileDevices[0] : nil;
        }
        _rowCount = 5;
    }

    for (ItemModel *condition in subItem.conditions) {
        if ([condition.itemSubTypeCode isEqualToString:ksConditionSubTypeCodeDueDate]) {//기간
            _dueDateCondition = condition;

            ItemSubModel *subCondition = _dueDateCondition.subItems[0];

            NSArray *darray = [subCondition.cmdclsValue componentsSeparatedByString:@"~"];

            //from
            [_btnDueDateFrom setTitle:darray[0] forState:UIControlStateNormal];
            if (darray.count > 1) {//to
                [_btnDueDateTo setTitle:darray[1] forState:UIControlStateNormal];
            }

            _chkDueDate.checked = YES;

            [_btnDueDateFrom setBackgroundImage:_imageBtnNormal forState:UIControlStateNormal];
            [_btnDueDateTo setBackgroundImage:_imageBtnNormal forState:UIControlStateNormal];

        } else if ([condition.itemSubTypeCode isEqualToString:ksConditionSubTypeCodeDaysOfWeek]) {//요일
            _daysOfWeekCondition = condition;
            ItemSubModel *subCondition = _daysOfWeekCondition.subItems[0];

            _chkDaysOfWeek.checked = YES;

            [_btnDaysOfWeek setTitle:subCondition.cmdclsValueMsg forState:UIControlStateNormal];
            [_btnDaysOfWeek setBackgroundImage:_imageBtnNormal forState:UIControlStateNormal];

        } else if ([condition.itemSubTypeCode isEqualToString:ksConditionSubTypeCodeDueTime]) {//시간
            _dueTimeCondition = condition;

            ItemSubModel *subCondition = _dueTimeCondition.subItems[0];

            NSArray *darray = [subCondition.cmdclsValue componentsSeparatedByString:@"~"];

            //from
            [_btnDueTimeFrom setTitle:darray[0] forState:UIControlStateNormal];
            if (darray.count > 1) {//to
                [_btnDueTimeTo setTitle:darray[1] forState:UIControlStateNormal];
            }

            _chkDueTime.checked = YES;

            [_btnDueTimeFrom setBackgroundImage:_imageBtnNormal forState:UIControlStateNormal];
            [_btnDueTimeTo setBackgroundImage:_imageBtnNormal forState:UIControlStateNormal];

        } else if ([condition.itemSubTypeCode isEqualToString:ksConditionSubTypeCodeHomeMode]) {//홈모드
            _homeModeCondition = condition;

            ItemSubModel *subCondition = _homeModeCondition.subItems[0];

            _chkModes.checked = YES;

            [_btnModes setTitle:subCondition.cmdclsValueMsg forState:UIControlStateNormal];
            [_btnModes setBackgroundImage:_imageBtnNormal forState:UIControlStateNormal];

        } else if ([condition.itemSubTypeCode isEqualToString:ksConditionSubTypeCodeExternHeat]) {//바깥온도
            _exterHeatCondition = condition;

            ItemSubModel *subCondition = _exterHeatCondition.subItems[0];

            _chkExternHeat.checked = YES;

            [_btnExternHeat setTitle:subCondition.cmdclsValueMsg forState:UIControlStateNormal];
            [_btnExternHeat setBackgroundImage:_imageBtnNormal forState:UIControlStateNormal];
        }
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

}

#pragma mark - Main Logic

- (BOOL)hasCondition {
    return _chkDueDate.checked || _chkDaysOfWeek.checked || _chkDueTime.checked || _chkModes.checked || _chkExternHeat.checked;
}

- (NSMutableArray<ItemModel> *)conditions {

    _conditions = [(NSMutableArray<ItemModel> *)[NSMutableArray alloc] init];

    //기간
    if (_chkDueDate.checked) {
        if (!self.dueDateCondition)
            return nil;
        [_conditions addObject:self.dueDateCondition];
    }

    //요일
    if (_chkDaysOfWeek.checked) {
        if (!self.daysOfWeekCondition)
            return nil;
        [_conditions addObject:self.daysOfWeekCondition];
    }

    //시간 조건
    if (_chkDueTime.checked) {
        if (!self.dueTimeCondition)
            return nil;
        [_conditions addObject:self.dueTimeCondition];
    }

    //홈모드
    if (_chkModes.checked) {
        if (!self.homeModeCondition)
            return nil;
        [_conditions addObject:self.homeModeCondition];
    }

    //지역온도모드
    if (_chkExternHeat.checked) {
        if (!self.exterHeatCondition)
            return nil;
        [_conditions addObject:self.exterHeatCondition];
    }
    return _conditions;
}

- (ItemModel *)dueDateCondition {
    _dueDateCondition = nil;

    if (_chkDueDate.checked) {
        _dueDateCondition = [[ItemModel alloc] init];
        _dueDateCondition.itemName = NSLocalizedString(@"기간", @"기간");
        _dueDateCondition.itemSubTypeCode = ksConditionSubTypeCodeDueDate;

        ItemSubModel *subCondtion = [[ItemSubModel alloc] init];
        subCondtion.conditionTypeCode = @"09";

        if ([[_btnDueDateTo titleForState:UIControlStateNormal] isEmptyString]) {
            subCondtion.cmdclsValue = [NSString stringWithFormat:@"%@", _btnDueDateFrom.dateString];
            subCondtion.dueDate = [NSString stringWithFormat:@"%@", _btnDueDateFrom.formatString];
        } else {
            subCondtion.cmdclsValue = [NSString stringWithFormat:@"%@~%@", _btnDueDateFrom.dateString, _btnDueDateTo.dateString];
            subCondtion.dueDate = [NSString stringWithFormat:@"%@ ~ %@", _btnDueDateFrom.formatString, _btnDueDateTo.formatString];
        }

        _dueDateCondition.subItems = (NSMutableArray<ItemSubModel> *)[[NSMutableArray alloc] initWithObjects:subCondtion, nil];
    }
    return _dueDateCondition;
}

//- (NSString *)dueDate {
//    _dueDate = nil;
//    if (_chkDueDate.checked) {
//        if (!_btnDueDateTo.value) {
//            _dueDate = [NSString stringWithFormat:@"%@", _btnDueDateFrom.dateString];
//        } else {
//            _dueDate = [NSString stringWithFormat:@"%@ ~ %@", _btnDueDateFrom.dateString, _btnDueDateTo.dateString];
//        }
//    }
//    return _dueDate;
//}
//
//
//- (NSString *)dueDateCommandClassValue {
//    _dueDateCommandClassValue = nil;
//    if (_chkDueDate.checked) {
//        if (!_btnDueDateTo.value) {
//            _dueDateCommandClassValue = [NSString stringWithFormat:@"%@", _btnDueDateFrom.formatString];
//        } else {
//            _dueDateCommandClassValue = [NSString stringWithFormat:@"%@ ~ %@", _btnDueDateFrom.formatString, _btnDueDateTo.formatString];
//        }
//    }
//    return _dueDateCommandClassValue;
//}

- (ItemModel *)daysOfWeekCondition {

    if (_chkDaysOfWeek.checked && _daysPopupView) {
        _daysOfWeekCondition = _daysPopupView.condition;
    }

    if (!_daysOfWeekCondition && _chkDaysOfWeek.checked) {
        [[JDFacade facade] alert:NSLocalizedString(@"요일을 선택해주세요", @"요일을 선택해주세요")];
    }

    return _daysOfWeekCondition;
}

//- (NSString *)daysOfWeek {
//    _daysOfWeek = nil;
//    if (_chkDaysOfWeek.checked) {
//        _daysOfWeek = _daysPopupView ? _daysPopupView.daysOfWeek : nil;
//    }
//    return _daysOfWeek;
//}
//
//- (NSString *)daysOfWeekCommandClassValue {
//    _daysOfWeekCommandClassValue = nil;
//    if (_chkDaysOfWeek.checked) {
//        _daysOfWeekCommandClassValue = _daysPopupView ? _daysPopupView.commandClassValue : nil;
//    }
//    return _daysOfWeekCommandClassValue;
//}

- (ItemModel *)dueTimeCondition {
    _dueTimeCondition = nil;
    if (_chkDueTime.checked) {
        _dueTimeCondition = [[ItemModel alloc] init];
        _dueTimeCondition.itemName = NSLocalizedString(@"시간", @"시간");
        _dueTimeCondition.itemSubTypeCode = ksConditionSubTypeCodeDueTime;

        ItemSubModel *subCondtion = [[ItemSubModel alloc] init];
        subCondtion.conditionTypeCode = @"09";

        if ([[_btnDueTimeTo titleForState:UIControlStateNormal] isEmptyString]) {
            subCondtion.cmdclsValue = [NSString stringWithFormat:@"%@", _btnDueTimeFrom.timeString];
            subCondtion.dueTime = [NSString stringWithFormat:@"%@", [CommonUtil formattedTime2:_btnDueTimeFrom.timeString]];
        } else {
            subCondtion.cmdclsValue = [NSString stringWithFormat:@"%@~%@", _btnDueTimeFrom.timeString, _btnDueTimeTo.timeString];
            subCondtion.dueTime = [NSString stringWithFormat:@"%@ ~ %@", [CommonUtil formattedTime2:_btnDueTimeFrom.timeString], [CommonUtil formattedTime2:_btnDueTimeTo.timeString]];
        }
        _dueTimeCondition.subItems = (NSMutableArray<ItemSubModel> *)[[NSMutableArray alloc] initWithObjects:subCondtion, nil];
    }
    return _dueTimeCondition;
}

//- (NSString *)dueTime {
//    _dueTime = nil;
//    if (_chkDueTime.checked) {
//
//        if (!_btnDueTimeTo.value) {
//            _dueTime = [NSString stringWithFormat:@"%@", _btnDueTimeFrom.timeString];
//        } else {
//            _dueTime = [NSString stringWithFormat:@"%@ ~ %@", _btnDueTimeFrom.timeString, _btnDueTimeTo.timeString];
//        }
//    }
//    return _dueDate;
//}
//
//- (NSString *)dueTimeCommandClassValue {
//    _dueTime = nil;
//    if (_chkDueTime.checked) {
//
//        if (!_btnDueTimeTo.value) {
//            _dueTime = [NSString stringWithFormat:@"%@", _btnDueTimeFrom.timeString];
//        } else {
//            _dueTime = [NSString stringWithFormat:@"%@ ~ %@", _btnDueTimeFrom.timeString, _btnDueTimeTo.timeString];
//        }
//    }
//    return _dueDate;
//}

- (ItemModel *)homeModeCondition {

    if (_chkModes.checked && _modePopTableView) {
        _homeModeCondition = _modePopTableView.condition;
    }

    if (!_homeModeCondition && _chkModes.checked) {
        [[JDFacade facade] alert:NSLocalizedString(@"홈모드를 선택해주세요", @"홈모드를 선택해주세요")];
    }


    return _homeModeCondition;
}

- (ItemModel *)exterHeatCondition {

    if (_chkExternHeat.checked && _externHeatPopView) {
        _exterHeatCondition = _externHeatPopView.condition;
    }

    if (!_exterHeatCondition && _chkExternHeat.checked) {
        [[JDFacade facade] alert:NSLocalizedString(@"지역온도를 선택해주세요", @"지역온도를 선택해주세요")];
    }

    return _exterHeatCondition;
}


- (CGFloat)heightForTriggerOptions
{
    return _rowCount * kfTriggerOptionTableViewCellHeight;
}



#pragma mark - UITableView Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _rowCount;
}

- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [super tableView:tableView indentationLevelForRowAtIndexPath:indexPath];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSIndexPath *tmpIndexPath = indexPath;

    if ([_tmpItem.itemSubTypeCode isEqualToString:ksItemSubTypeCodeTimer]) {

        if (indexPath.row >= 2) {
            tmpIndexPath = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:indexPath.section];
        }

    } else if ([_tmpItem.itemSubTypeCode isEqualToString:ksItemSubTypeCodeMode]) {
        if (indexPath.row >= 3) {
            tmpIndexPath = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:indexPath.section];
        }
    }

    UITableViewCell *cell  = [super tableView:tableView cellForRowAtIndexPath:tmpIndexPath];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

    // Remove seperator inset
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }

    // Prevent the cell from inheriting the Table View's margin settings
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }

    // Explictly set your cell's layout margins
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}



#pragma mark - UI Events
- (IBAction)chkDueDateTouched:(id)sender
{
    CustomCheckBox *chk = (CustomCheckBox *)sender;
    UIImage *image = !chk.checked ? _imageBtnNormal : _imageBtnDisable;

    if (!chk.checked) {
        [_btnDueDateTo setTitle:ksEmptyString forState:UIControlStateNormal];
    }

    [_btnDueDateFrom setBackgroundImage:image forState:UIControlStateNormal];
    [_btnDueDateTo setBackgroundImage:image forState:UIControlStateNormal];
}

- (IBAction)chkDaysTouched:(id)sender
{
    CustomCheckBox *chk = (CustomCheckBox *)sender;
    UIImage *image = !chk.checked ? _imageBtnNormal : _imageBtnDisable;

    [_btnDaysOfWeek setBackgroundImage:image forState:UIControlStateNormal];
}

- (IBAction)chkDueTimeTouched:(id)sender
{
    CustomCheckBox *chk = (CustomCheckBox *)sender;
    UIImage *image = !chk.checked ? _imageBtnNormal : _imageBtnDisable;

    if (!chk.checked) {
        [_btnDueTimeTo setTitle:ksEmptyString forState:UIControlStateNormal];
    }

    [_btnDueTimeFrom setBackgroundImage:image forState:UIControlStateNormal];
    [_btnDueTimeTo setBackgroundImage:image forState:UIControlStateNormal];
}

- (IBAction)chkModesTouched:(id)sender
{
    CustomCheckBox *chk = (CustomCheckBox *)sender;
    UIImage *image = !chk.checked ? _imageBtnNormal : _imageBtnDisable;

    [_btnModes setBackgroundImage:image forState:UIControlStateNormal];
}

- (IBAction)chkExternHeatTouched:(id)sender
{
    CustomCheckBox *chk = (CustomCheckBox *)sender;
    UIImage *image = !chk.checked ? _imageBtnNormal : _imageBtnDisable;

    [_btnExternHeat setBackgroundImage:image forState:UIControlStateNormal];
}


//buttons
- (IBAction)btnDueDateFromTouched:(id)sender
{
    CustomButton *btn = (CustomButton *)sender;
    [btn setBackgroundImage:_imageBtnNormal forState:UIControlStateNormal];

    _chkDueDate.checked = YES;
}

- (IBAction)btnDueDateToTouched:(id)sender
{
    CustomButton *btn = (CustomButton *)sender;
    [btn setBackgroundImage:_imageBtnNormal forState:UIControlStateNormal];
    [_btnDueDateFrom setBackgroundImage:_imageBtnNormal forState:UIControlStateNormal];

    _chkDueDate.checked = YES;
}

- (IBAction)btnDaysToTouched:(id)sender
{
    CustomButton *btn = (CustomButton *)sender;
   [btn setBackgroundImage:_imageBtnNormal forState:UIControlStateNormal];

    _chkDaysOfWeek.checked = YES;

    if (!_daysPopupView) {
        _daysPopupView = [[DaysPopupView alloc] initFromNib];
    }

    _daysPopupView.condition = _daysOfWeekCondition;
    [_daysPopupView showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//선택
            _daysOfWeekCondition = _daysPopupView.condition;
            [_btnDaysOfWeek setTitle:_daysPopupView.daysOfWeek forState:UIControlStateNormal];
        }
    }];
}

- (IBAction)btnDueTimeFromToTouched:(id)sender
{
    CustomButton *btn = (CustomButton *)sender;
    [btn setBackgroundImage:_imageBtnNormal forState:UIControlStateNormal];
    _chkDueTime.checked = YES;
}

- (IBAction)btnDueTimeToTouched:(id)sender
{
    CustomButton *btn = (CustomButton *)sender;
    [btn setBackgroundImage:_imageBtnNormal forState:UIControlStateNormal];
    [_btnDueTimeTo setBackgroundImage:_imageBtnNormal forState:UIControlStateNormal];

    _chkDueTime.checked = YES;
}

- (IBAction)btnModesTouched:(id)sender
{
    CustomButton *btn = (CustomButton *)sender;
    [btn setBackgroundImage:_imageBtnNormal forState:UIControlStateNormal];

    _chkModes.checked = YES;

    if (!_modePopTableView) {
        _modePopTableView = [[ModePopTableView alloc] initFromNib];
    }

    _modePopTableView.condition = _homeModeCondition;
    [_modePopTableView showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//선택

            _homeModeCondition = _modePopTableView.condition;
            [_btnModes setTitle:_modePopTableView.homeModes forState:UIControlStateNormal];
        }
    }];
}

- (IBAction)btnExternHeatTouched:(id)sender
{
    CustomButton *btn = (CustomButton *)sender;
    [btn setBackgroundImage:_imageBtnNormal forState:UIControlStateNormal];

    _chkExternHeat.checked = YES;

    if (!_externHeatPopView) {
        _externHeatPopView = [[ExternHeatPopupView alloc] initFromNib];
    }

    _externHeatPopView.condition = _exterHeatCondition;
    [_externHeatPopView showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//선택

            _exterHeatCondition = _externHeatPopView.condition;
            [_btnExternHeat setTitle:_externHeatPopView.externHeat forState:UIControlStateNormal];
        }
    }];
}


#pragma mark - MemoryWarning
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
