//
//  RulesRegisterTimerViewController.m
//  kneet
//
//  Created by Jason Lee on 3/24/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
@import QuartzCore;

#import "JDObject.h"
#import "RuleModel.h"
#import "ItemModel.h"

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

#import "RulesTriggerOptionViewController.h"

#import "RegisterTimerViewController.h"

@implementation CustomDatePicker

- (void)awakeFromNib {
    self.layer.backgroundColor = [UIColor clearColor].CGColor;
}
- (void)addSubview:(UIView *)view {

    if (!changed) {
        changed = YES;
        [self setValue:[UIColor whiteColor] forKey:@"textColor"];
    }
    [super addSubview:view];
}

@end


@implementation RegisterTimerTitleTableViewCell


@end

@implementation RegisterPickerTableViewCell


@end

@interface RegisterTriggerActivationTableViewCell () {

}

@end

@implementation RegisterTriggerActivationTableViewCell

- (void)awakeFromNib {
    _btnAddTriggerImageNormal = [UIImage imageNamed:@"common_list_btn_s_add"];
    _btnAddTriggerImageHighlight = [UIImage imageNamed:@"common_list_btn_s_add_press"];
    _btnDeleteTriggerImageNormal = [UIImage imageNamed:@"common_list_btn_del"];
    _btnDeleteTriggerImageHighlight = [UIImage imageNamed:@"common_list_btn_del_press"];
    
    _lblDesc.text = NSLocalizedString(@"특정 날짜나 요일에만 실행하려면\n추가 조건을 걸어보세요", @"특정 날짜나 요일에만 실행하려면\n추가 조건을 걸어보세요");
}

- (void)setTriggerOptionEnable:(BOOL)enable {
    if (!enable) {
        [self.btnTriggerOption setImage:_btnAddTriggerImageNormal forState:UIControlStateNormal];
        [self.btnTriggerOption setImage:_btnAddTriggerImageHighlight forState:UIControlStateHighlighted];

    } else {
        [self.btnTriggerOption setImage:_btnDeleteTriggerImageNormal forState:UIControlStateNormal];
        [self.btnTriggerOption setImage:_btnDeleteTriggerImageHighlight forState:UIControlStateHighlighted];
    }
}

@end

@implementation RegisterContainerTableViewCell

@end


@interface RegisterTimerViewController () <UIPickerViewDelegate, UITableViewDataSource, UITableViewDelegate> {
    NSInteger _sectionCount;

    CustomDatePicker *_timePicker;
    RulesTriggerOptionViewController *_triggervc;


    BOOL _isNotFirstLoading;
}
@end


#pragma mark - Class Definition

@implementation RegisterTimerViewController


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

    [self initUI];
    [self prepareViewDidLoad];
}


- (void)initUI {

    
    

    self.tableView.delegate = self;
    self.tableView.dataSource = self;

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor clearColor];

    self.tableView.tableFooterView = [[UIView alloc] init]; //this call table events;
    
    [_timePicker setTimeZone:[NSTimeZone systemTimeZone]];
    
    //Localization
    [_btnSelect setTitle:NSLocalizedString(@"선택완료", @"선택완료") forState:UIControlStateNormal];
    [_btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
}

- (void)prepareViewDidLoad {

    ItemSubModel *subItem = _tmpItem.timers[0];

    _sectionCount = subItem.conditions && subItem.conditions.count ? 4 : 3;
    if (!_tmpItem.timers || !_tmpItem.timers.count)
        return;
}

#pragma mark - Main Logic

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

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

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    CGFloat height = 0.0f;

    if (indexPath.section == 0) {
        height = 75.0f;

    } else if (indexPath.section == 1) {
        height = 210.0f;

    } else if (indexPath.section == 2) {//activation cell
        height = 80.0f;

    } else if (indexPath.section == 3) {//container
        height = 240;
    }
    return height;
}

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

    UITableViewCell *cell = nil;

    if (indexPath.section == 0) {

        RegisterTimerTitleTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"TitleCellIdentifier" forIndexPath:indexPath];
        if (!tcell) {
            tcell = (RegisterTimerTitleTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"TitleCellIdentifier"];
        }
        tcell.lblItemTitle.text = _tmpItem.itemName;
        cell = tcell;

    } else if (indexPath.section == 1) {
        RegisterPickerTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"PickerCellIdentifier" forIndexPath:indexPath];
        if (!tcell) {
            tcell = (RegisterPickerTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"PickerCellIdentifier"];
        }

        if (!_isNotFirstLoading) {//처음 로딩 시,
            _isNotFirstLoading = YES;

            ItemSubModel *subItem = _tmpItem.timers[0];
            NSDateComponents *ds = [CommonUtil dateComponents:[NSDate date] timezone:[NSTimeZone systemTimeZone]];
            ds.hour = [subItem.hour integerValue];
            ds.minute = [subItem.minute integerValue];
            tcell.timePicker.date = [[NSCalendar currentCalendar] dateFromComponents:ds];
        }

        _timePicker = tcell.timePicker;

        cell = tcell;

    } else if (indexPath.section == 2) {//activation
        RegisterTriggerActivationTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"ActivationCellIdentifier" forIndexPath:indexPath];
        if (!tcell) {
            tcell = (RegisterTriggerActivationTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"ActivationCellIdentifier"];
        }

        if (![tcell.btnTriggerOption actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
            [tcell.btnTriggerOption addTarget:self action:@selector(btnAddTriggerOptionTouched:) forControlEvents:UIControlEventTouchUpInside];
        }

        //이미지 전환
        [tcell setTriggerOptionEnable:_sectionCount == 4];
        cell = tcell;
    } else if (indexPath.section == 3) {//container
        RegisterContainerTableViewCell *tcell = (RegisterContainerTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"ContainerCellIdentifier"];

        if (!_triggervc) {//트리거뷰를 로드함.
            _triggervc = (RulesTriggerOptionViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"RulesTriggerOptionViewController" storyboardName:@"Rules"];
            _triggervc.tmpItem = _tmpItem;

            [self addChildViewController:_triggervc];
            [_triggervc didMoveToParentViewController:self];

            if ([self isViewLoaded] && tcell.triggerOptionContainer) {
                [_triggervc beginAppearanceTransition:YES animated:NO];
                [tcell.triggerOptionContainer addSubview:_triggervc.view];
                [_triggervc endAppearanceTransition];
                [_triggervc.view mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.size.mas_equalTo(tcell.triggerOptionContainer);
                    make.center.equalTo(tcell.triggerOptionContainer);
                }];
            }
        }

        cell = tcell;
    }

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (indexPath.section == 2) {//activationCell
        RegisterTriggerActivationTableViewCell *tcell = (RegisterTriggerActivationTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
        [self btnAddTriggerOptionTouched:tcell.btnTriggerOption];
    }
}

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

    _sectionCount = _sectionCount == 3 ? 4 : 3;
    [self.tableView reloadData];

    if (_sectionCount == 4) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:3];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}

- (void)btnSelectTouched:(id)sender {

    //컨디션을 설정함 - 이전 선택된 컨디션을 유지하기 위해 먼저 확인 - 테이블 뷰의 특성상.
    NSMutableArray<ItemModel> *conditions = nil;
    if (_triggervc && [_triggervc hasCondition]) {//트리거를 선택했을 경우,
        if (!_triggervc.conditions) {
            return;
        }

        conditions = _triggervc.conditions;
    } else {
        if (_tmpItem.timers && _tmpItem.timers.count && !_triggervc) {
            ItemSubModel *tmpSubItem = _tmpItem.timers[0];
            conditions = tmpSubItem.conditions;
        }
    }

    //time
    NSDateComponents *ds = [CommonUtil dateComponents:_timePicker.date timezone:[NSTimeZone systemTimeZone]];

    ItemSubModel *subItem = [[ItemSubModel alloc] init];
    subItem.hour = [NSString stringWithFormat:@"%zd", ds.hour];
    subItem.minute = [NSString stringWithFormat:@"%zd", ds.minute];


    if (conditions) {
        subItem.conditions = conditions;
    }
    _tmpItem.timers = (NSMutableArray<ItemSubModel> *)[[NSMutableArray alloc] initWithArray:@[subItem]];

    [self.navigationController popViewControllerAnimated:YES];
}


- (void)btnCancelTouched:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


- (IBAction)btnHourUpTouched:(id)sender {

//    NSDateComponents *ds = [CommonUtil dateComponents:_timePicker.date];
//    ds.hour += 1;
//    _timePicker.date = [[NSCalendar currentCalendar] dateFromComponents:ds];
}


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

@end
