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

#import "CustomLabel.h"
#import "CustomImageView.h"
#import "UIImageView+WebCache.h"
#import "JYRefreshController.h"


#import "RulesRegisterPredefineViewController.h"

#import "RulesRegisterViewController.h"
#import "ImageUtil.h"

@implementation PredefinedTitleViewCell

- (void)awakeFromNib {
    _lblTitle.text = NSLocalizedString(@"샘플 규칙을 선택하세요", @"샘플 규칙을 선택하세요");
    self.backgroundColor = [UIColor clearColor];   
}
@end

@implementation PredefinedTableViewCell

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

@end

@interface RulesRegisterPredefineViewController () <UITableViewDataSource, UITableViewDelegate> {
    NSString *_pagingType, *_pagingId;
    NSMutableArray<RuleModel> *_predefinedRuleList;
    UIImage *_bgCellImage1, *_bgCellImage2;
}

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

@end


#pragma mark - Class Definition

@implementation RulesRegisterPredefineViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    _predefinedRuleList = (NSMutableArray<RuleModel> *)[[NSMutableArray alloc] init];

    [self initUI];
    [self prepareViewDidLoad];
}

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

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

- (void)initUI {

    //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 requestPredefinedRulesRecently];
    };
    
    self.loadMoreController = [[JYPullToLoadMoreController alloc] initWithScrollView:self.tableView];
    self.loadMoreController.pullToLoadMoreHandleAction = ^{
        [weakSelf requestPredefinedRulesOlder];
    };

    UIEdgeInsets insets = UIEdgeInsetsMake(4, 4, 4, 4);
    _bgCellImage1 = [ImageUtil resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch img:[UIImage imageNamed:@"tp_01_img_list_bg_01"]];
    _bgCellImage2 = [ImageUtil resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch img:[UIImage imageNamed:@"tp_01_img_list_bg_02"]];
}

- (void)prepareViewDidLoad {
    [self performSelector:@selector(requestPredefinedRules) withObject:nil afterDelay:0.0f];
}

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

    RuleModel *firstRule = [_predefinedRuleList firstObject];
    _pagingType = ksListPagingTypeUpward;
    _pagingId = firstRule.predRuleId;

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

- (void)requestPredefinedRulesOlder {

    RuleModel *lastRule = [_predefinedRuleList lastObject];
    _pagingType = ksListPagingTypeDownward;
    _pagingId = lastRule.predRuleId;

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

- (void)requestPredefinedRules {

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

    NSString *path = [NSString stringWithFormat:API_GET_PRERULE_LIST];

    [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:parameter modelClass:[RuleListModel class] completion:^(id responseObject) {

        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }

        RuleListModel *fetchedPreRuleList = (RuleListModel *)responseObject;

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

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

        [_tableView reloadData];

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

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _predefinedRuleList.count + 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 100.0f;
    if (indexPath.row == 0) {
        height = 40.0f;
    }
    return height;
}

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


    UITableViewCell *cell = nil;

    if (indexPath.row == 0) {//info cell
        cell = [tableView dequeueReusableCellWithIdentifier:@"InfoCellIdentifier"];
    } else {
        PredefinedTableViewCell *pcell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];

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

        RuleModel *predefinedRule = _predefinedRuleList[indexPath.row-1];
        pcell.lblRuleName.text = predefinedRule.ruleName;
        [pcell.imgvIcon sd_setImageWithURL:[NSURL URLWithString:predefinedRule.imageFileName] placeholderImage:nil];

        cell = pcell;
    }

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

    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;
}

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

    if (indexPath.row == 0)
        return;

    //goto rule title register
    RulesRegisterViewController *vc = (RulesRegisterViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"RulesRegisterViewController" storyboardName:@"Rules"];

    RuleModel *predefinedRule = _predefinedRuleList[indexPath.row-1];
    vc.tmpPredRule = predefinedRule;

    [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
