//
//  RulesViewController.m
//  kneet
//
//  Created by Jason Lee on 3/18/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "JDObject.h"
#import "RequestHandler.h"
#import "RuleModel.h"

#import "CustomLabel.h"
#import "CustomImageView.h"
#import "JYRefreshController.h"

#import "RulesDetailViewController.h"

#import "RulesViewController.h"
#import "ImageUtil.h"


#define kfRulesTableViewCellHeight 100.0f

@implementation RulesTableViewCell

- (void)awakeFromNib {
    self.backgroundColor = [UIColor clearColor];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
}

@end

@implementation RulesAddTableViewCell

- (void)awakeFromNib {
    self.backgroundColor = [UIColor clearColor];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
    _lblDesc.text = NSLocalizedString(@"원하는 시점에 알아서 실행되도록\n홈 규칙을 만들어 보세요!", @"원하는 시점에 알아서 실행되도록\n홈 규칙을 만들어 보세요!");
}

- (void)btnAddTouched:(id)sender {
    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"RuleRegisterTypeViewController" storyboardName:@"Rules"];
    [[JDFacade facade].currentViewController.navigationController pushViewController:vc animated:YES];
}

@end

@interface RulesViewController () <UITableViewDataSource, UITableViewDelegate> {
    NSString *_pagingType, *_pagingId;
    NSMutableArray<RuleModel> *_ruleList;
    UIImage *_bgCellImage1, *_bgCellImage2;
    UIImage *_stateImageRun, *_stateImageStop, *_stateImageDisable;
}

@property (strong, nonatomic) JYPullToRefreshController *refreshController;
@property (strong, nonatomic) JYPullToLoadMoreController *loadMoreController;

@end


#pragma mark - Class Definition

@implementation RulesViewController


- (void)viewDidLoad {
    [super viewDidLoad];

    _ruleList = (NSMutableArray<RuleModel> *)[[NSMutableArray alloc] init];

    [self initUI];
    [self prepareViewDidLoad];
}

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

    self.title = NSLocalizedString(@"홈 규칙",nil);
}

- (void)initUI {
    
    [self generateOptionButton];

    //initialize tableview
    _tableView.dataSource = self;
    _tableView.delegate = self;

    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor clearColor];

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

    //set refresh controls
    __weak typeof(self) weakSelf = self;
    self.refreshController = [[JYPullToRefreshController alloc] initWithScrollView:self.tableView];
    self.refreshController.pullToRefreshHandleAction = ^{
        [weakSelf requestRuleListRecently];
    };
    
    self.loadMoreController = [[JYPullToLoadMoreController alloc] initWithScrollView:self.tableView];
    self.loadMoreController.pullToLoadMoreHandleAction = ^{
        [weakSelf requestRuleListOlder];
    };

    UIEdgeInsets insets = UIEdgeInsetsMake(4, 4, 4, 4);
    _bgCellImage1 = [ImageUtil resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch img:[UIImage imageNamed:@"tp_01_img_list_bg_02"]];
    _bgCellImage2 = [ImageUtil resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch img:[UIImage imageNamed:@"tp_01_img_list_bg_01"]];
    
    _stateImageRun = [UIImage imageNamed:@"tp_01_img_icon_rule_condition_play"];
    _stateImageStop = [UIImage imageNamed:@"tp_01_img_icon_rule_condition_stop"];
    _stateImageDisable = [UIImage imageNamed:@"tp_01_img_icon_rule_condition_disable"];
    
    [self setThingsPopoverOptions];
}

- (void)setThingsPopoverOptions {
    //set Popover Contents
    __weak typeof(self) weakSelf = self;
    _popooverOptionArray = [[NSMutableArray alloc] init];

    [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"새로 고침",nil),
                                      @"iconName": @"tp_01_img_bg_morepopup_icon_refresh",
                                      @"target": weakSelf,
                                      @"selector": [NSValue valueWithPointer:@selector(refreshRuleList)]}];

    if ([JDFacade facade].loginUser.level > 10) {//파워유저 이상일 경우,
        [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"새 규칙 추가",nil),
                                          @"iconName": @"tp_01_img_bg_morepopup_icon_group_deviceadd",
                                          @"target": weakSelf,
                                          @"selector": [NSValue valueWithPointer:@selector(addNewRule)]}];
    }
}

- (void)prepareViewDidLoad {
    if (_ruleList && _ruleList.count) {
        [_ruleList removeAllObjects];
    }
    [self performSelector:@selector(requestRules) withObject:nil afterDelay:0.0f];
}

- (void)updateHomeHubStatusToRules {
    
}


- (void)refreshRuleList {
    _pagingId = nil;
    _pagingType = nil;

    if (_ruleList && _ruleList.count) {
        [_ruleList removeAllObjects];
    }
    [self performSelector:@selector(requestRules) withObject:nil afterDelay:0.0f];
}

- (void)addNewRule {
    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"RuleRegisterTypeViewController" storyboardName:@"Rules"];
    [[JDFacade facade].currentViewController.navigationController pushViewController:vc animated:YES];
}

#pragma mark - Main Logic
- (void)requestRuleListRecently {

    RuleModel *firstRule = [_ruleList firstObject];
    _pagingType = ksListPagingTypeUpward;
    _pagingId = firstRule.ruleId;

    [self performSelector:@selector(requestRules) withObject:nil afterDelay:0.0f];
}

- (void)requestRuleListOlder {

    RuleModel *lastRule = [_ruleList lastObject];
    _pagingType = ksListPagingTypeDownward;
    _pagingId = lastRule.ruleId;

    [self performSelector:@selector(requestRules) withObject:nil afterDelay:0.0f];
}

- (void)requestRules {

    NSDictionary *parameter = @{@"rule_id": _pagingId ? _pagingId : ksEmptyString,
                                @"paging_type": _pagingType ? _pagingType : ksEmptyString};

    NSString *path = [NSString stringWithFormat:API_GET_RULE];

    [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:parameter modelClass:[RuleListModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }

        RuleListModel *fetchedRuleList = (RuleListModel *)responseObject;

        if (fetchedRuleList && fetchedRuleList.list && fetchedRuleList.list.count) {//API 성공,
            [_ruleList addObjectsFromArray:fetchedRuleList.list];

        } else {//실패 시,
            if (!_ruleList.count) {//이미 로드된 데이터가 있을 경우는 출력하지 않음.
//                NoContentView *noContentView = [NoContentView viewFromNib];
//                _tableView.tableFooterView = noContentView;
            }
        }

        [_tableView reloadData];

    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

- (void)updateRule:(RuleModel *)rule {
    for (RuleModel *tmpRule in _ruleList) {
        if ([rule.homegrpRuleId isEqualToString:tmpRule.homegrpRuleId]) {
            tmpRule.ruleName = rule.ruleName;
            tmpRule.useYn = rule.useYn;
            break;
        }
    }

    [_tableView reloadData];
}


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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _ruleList.count + ([JDFacade facade].loginUser.level > 10 ? 1 : 0);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = kfRulesTableViewCellHeight;

    if (indexPath.row == _ruleList.count) {
        height = _ruleList.count ? 190.0f : IPHONE_HEIGHT - kfNavigationBarHeight;
        _tableView.scrollEnabled = _ruleList.count;
    }
    return height;
}

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

    UITableViewCell *cell = nil;

    if (indexPath.row < _ruleList.count) {
        RulesTableViewCell *rcell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];

        if (rcell == nil) {
            rcell = [[RulesTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellIdentifier"];
        }

        RuleModel *rule = _ruleList[indexPath.row];

        rcell.lblRuleName.text = rule.ruleName;
        rcell.lblRuleName.textColor = [UIColor whiteColor];
        rcell.imgvState.image = [rule.useYn boolValue] ? _stateImageRun : _stateImageStop;
        rcell.imgvState.image = [rule.useYn isEqualToString:ksKneetRulesDisable] ? _stateImageDisable : rcell.imgvState.image;
        cell = rcell;

        //set background image
        if (indexPath.row % 2 == 1) {
            cell.backgroundView = [[UIImageView alloc] initWithImage:_bgCellImage1];
        } else {
            cell.backgroundView = [[UIImageView alloc] initWithImage:_bgCellImage2];
        }

    } else {
        RulesAddTableViewCell *acell = [tableView dequeueReusableCellWithIdentifier:@"AddCellIdentifier"];

        if (acell == nil) {
            acell = [[RulesAddTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"AddCellIdentifier"];
        }
        cell = acell;
    }

    return cell;
}

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

    if (indexPath.row == _ruleList.count) {
        return;
    }

    //goto rule details
    RulesDetailViewController *vc = (RulesDetailViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"RulesDetailViewController" storyboardName:@"Rules"];
    vc.rule = _ruleList[indexPath.row];

    [self.navigationController pushViewController:vc animated:YES];
}


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



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

@end
