//
//  HomeLogsViewController.m
//  kneet
//
//  Created by Jason Lee on 4/28/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "JDObject.h"
#import "RequestHandler.h"
#import "ModeModel.h"

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

#import "HomeLogsViewController.h"

@implementation HomeLogsHeaderTableView

@end

@implementation HomeLogsRuleTableViewCell

- (void)awakeFromNib {
    self.selectionStyle = UITableViewCellSelectionStyleNone;
}

@end

@implementation HomeLogsMemberTableViewCell
- (void)awakeFromNib {
    self.selectionStyle = UITableViewCellSelectionStyleNone;
}
@end

@implementation HomeLogsHomeTableViewCell
- (void)awakeFromNib {
    self.selectionStyle = UITableViewCellSelectionStyleNone;
}
@end

@interface HomeLogsViewController () <UITableViewDataSource, UITableViewDelegate> {
    NSString *_pagingType, *_pagingDateTime;
    NSMutableArray *_dataArray;
    UIImage *_bgCellImage1, *_bgCellImage2;
}

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

@end


#pragma mark - Class Definition

@implementation HomeLogsViewController


- (void)viewDidLoad {
    [super viewDidLoad];

    _dataArray = [[NSMutableArray alloc] init];

    [self initUI];
    [self prepareViewDidLoad];
}

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

    self.title = NSLocalizedString(@"홈 로그",nil);
}

- (void)initUI {

    //set tableview option
    _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 requestHomelogsRecently];
    };
    
    self.loadMoreController = [[JYPullToLoadMoreController alloc] initWithScrollView:self.tableView];
    self.loadMoreController.pullToLoadMoreHandleAction = ^{
        [weakSelf requestHomelogsOlder];
    };
    

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

- (void)prepareViewDidLoad {

    [self performSelectorOnMainThread:@selector(requestHomelogs) withObject:nil waitUntilDone:0.0f];
//    _dataArray = [[NSMutableArray alloc] init];
//
//    NSArray *today = @[@{@"type": @"rule",  @"time": @"17:30", @"icon": @"tp_01_img_homelog_icon_rule", @"title": @"규칙이 실행되었습니다.", @"desc" : @"상쾌한 아침\n상쾌한 아침"},
//                       @{@"type": @"rule",  @"time": @"14:30", @"icon": @"tp_01_img_homelog_icon_rule", @"title": @"규칙이 실행되었습니다.규칙이 실행되었습니다.규칙이 실행되었습니다.", @"desc" : @"상쾌한 아침\n상쾌한 아침\n상쾌한 아침"},
//                       @{@"type": @"member",@"time": @"12:30", @"icon": @"tp_01_img_homelog_icon_member", @"title": @"새로운 멤버가 참여했습니다.", @"desc" : @"파워유저",
//                         @"member_role": @"파워유저", @"member_name": @"[막둥이]", @"member_icon": @"tp_01_img_singup_membericon_01"},
//                       @{@"type": @"member",@"time": @"12:30", @"icon": @"tp_01_img_homelog_icon_member", @"title": @"새로운 멤버가 참여했습니다.새로운 멤버가 참여했습니다.새로운 멤버가 참여했습니다.", @"desc" : @"파워유저",
//                         @"member_role": @"파워유저", @"member_name": @"[막둥이]", @"member_icon": @"tp_01_img_singup_membericon_01"},
//                       @{@"type": @"member",@"time": @"12:30", @"icon": @"tp_01_img_homelog_icon_member", @"title": @"새로운 멤버가 참여했습니다.", @"desc" : @"파워유저",
//                         @"member_role": @"파워유저", @"member_name": @"[막둥이]", @"member_icon": @"tp_01_img_singup_membericon_01"},
//                       @{@"type": @"home",  @"time": @"11:30", @"icon": @"tp_01_img_homelog_icon_home", @"title": @"[즐거운 나의 하우스] 시작합니다!", @"desc" : @"상쾌한 아침",
//                         @"member_role": @"최고관리자", @"member_name": @"[아빠]", @"member_icon": @"tp_01_img_singup_membericon_01"},
//                       @{@"type": @"home",  @"time": @"11:30", @"icon": @"tp_01_img_homelog_icon_home", @"title": @"[즐거운 나의 하우스] 시작합니다![즐거운 나의 하우스] 시작합니다!", @"desc" : @"상쾌한 아침",
//                         @"member_role": @"최고관리자", @"member_name": @"[아빠]", @"member_icon": @"tp_01_img_singup_membericon_01"},
//                       @{@"type": @"home",  @"time": @"11:30", @"icon": @"tp_01_img_homelog_icon_home", @"title": @"[즐거운 나의 하우스] 시작합니다![즐거운 나의 하우스] 시작합니다![즐거운 나의 하우스] 시작합니다!", @"desc" : @"상쾌한 아침",
//                         @"member_role": @"최고관리자", @"member_name": @"[아빠]", @"member_icon": @"tp_01_img_singup_membericon_01"},
//                       ];
//
//    [_dataArray addObject:@{@"date": @"today", @"list": today}];
//    [_dataArray addObject:@{@"date": @"yesterday", @"list": today}];
//    [_dataArray addObject:@{@"date": @"2015.05.04", @"list": today}];
//    [_dataArray addObject:@{@"date": @"2015.05.03", @"list": today}];
}

#pragma mark - Main Logic

- (void)requestHomelogsRecently {
    NSDictionary *homeDic = [_dataArray firstObject];
    HomeLogModel *firstHomelog = [homeDic[@"list"] firstObject];
    _pagingType = ksListPagingTypeUpward;
    _pagingDateTime = firstHomelog.createDatetime;

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

- (void)requestHomelogsOlder {
    NSDictionary *homeDic = [_dataArray lastObject];
    HomeLogModel *lastHomelog = [homeDic[@"list"] lastObject];

    _pagingType = ksListPagingTypeDownward;
    _pagingDateTime = lastHomelog.createDatetime;

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

- (void)requestHomelogs {

    //parameters
    NSDictionary *parameter = @{@"paging_datetime": _pagingDateTime ? _pagingDateTime : ksEmptyString,
                                @"paging_type": _pagingType ? _pagingType : ksEmptyString};

    NSString *path = [NSString stringWithFormat:API_GET_HOMELOG];

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

        HomeLogListModel *fetchedList = (HomeLogListModel *) responseObject;

        if (fetchedList && fetchedList.homelogList && fetchedList.homelogList.count) {//API 성공,
            //sort.
            [self sortHomelogs:fetchedList.homelogList];

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


        NSInteger count = 0;
        for (NSDictionary *dic in _dataArray) {
            count += [dic[@"list"] count];
        }

        [_tableView reloadData];

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

}

- (void)sortHomelogs:(NSArray<HomeLogModel> *)homelogList {
    //날짜 비교를 위한 Array 생성.
    NSMutableArray *dateArray = [[NSMutableArray alloc] initWithArray:[_dataArray valueForKeyPath:@"createDate"]];

    //동일 날짜일 경우, 배열 맨 위부터 추가를 위한 인덱스.
    NSInteger i = 0;
    
    for (HomeLogModel *homelog in homelogList) {
        NSInteger index  = [dateArray indexOfObjectPassingTest:^BOOL(NSString *date, NSUInteger idx, BOOL *stop) {
            return [homelog.createDate isEqualToString:date];
        }];

        //case 최신 - 새로운 create가 여러개일 경우 - 첫 데이터는 날짜를 추가 후 이후 같은 날짜 데이터는 배열에 추가해줌.
        //case 이전 - 기존에 존재하는 date가 여러개일 경우, - 해당 배열에 인덱스 추가.
        if (index == NSNotFound) {//새로 추가
            
            //새로운 날짜가 추가될 경우, 인덱스 카운트를 0으로 리셋
            i = 0;
            
            NSMutableArray<HomeLogModel> *homelogs = (NSMutableArray<HomeLogModel> *)[[NSMutableArray alloc] init];
            [homelogs addObject:homelog];

            if ([_pagingType isEqualToString:ksListPagingTypeUpward]) {//최신일 경우 - 다른 날짜일 경우, 배열 맨 위부터 추가
                [_dataArray insertObject:@{@"createDate": homelog.createDate,
                                           @"list": homelogs} atIndex:i];   //-dateListDic
                [dateArray insertObject:homelog.createDate atIndex:i];
                
                //increase index of array.
                i++;
            } else {//이전 데이터일 경우, 배열 뒤에 추가
                [_dataArray addObject:@{@"createDate": homelog.createDate,
                                        @"list": homelogs}];
                [dateArray addObject:homelog.createDate];
            }
            
        } else {//add
            
            NSDictionary *dateListDic = _dataArray[index];
            NSMutableArray<HomeLogModel> *homelogs = dateListDic[@"list"];
            
            if ([_pagingType isEqualToString:ksListPagingTypeUpward]) {//최신일 경우 - 동일 날짜일 경우, 배열 맨 위부터 추가,
                [homelogs insertObject:homelog atIndex:i++];
            } else {//이전 데이터일 경우, 배열 뒤에 추가
                [homelogs addObject:homelog];
            }
        }
    }
    NSLog(@"%s\n %@", __PRETTY_FUNCTION__, _dataArray);
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    NSInteger count = 0;
    NSDictionary *homeDic = _dataArray[section];
    NSMutableArray<HomeLogModel> *homelogs = homeDic[@"list"];
    count = homelogs.count;

    return count;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    NSDictionary *homeDic = _dataArray[section];

    HomeLogsHeaderTableView *hcell = (HomeLogsHeaderTableView *)[tableView dequeueReusableCellWithIdentifier:@"HomeLogsHeaderCellIdentifier"];
    hcell.lblHeader.text = homeDic[@"createDate"];

    return hcell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    return 60.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01f;
}

- (CGFloat)calculateTitleHeight:(NSString *)title {
    if ([title isEmptyString]) {
        return 0.0f;
    }

    CGFloat width = IPHONE_WIDTH - 20 - 40 - 35 - 10 - 10 - 20 - 10;

    UIFont *lfont = [UIFont boldSystemFontOfSize:kUIFontSize01];
    CGFloat nheight = [CommonUtil getSizeFromString:title font:lfont width:width].height;
    nheight = nheight < 20 ? 20.0f : fabs(nheight) + 1.0f; //adjust padding
    return nheight;
}

- (CGFloat)calculateDescHeight:(NSString *)desc {
    if ([desc isEmptyString]) {
        return 0.0f;
    }

    CGFloat width = IPHONE_WIDTH - 20 - 40 - 35 - 10 - 10 - 20 - 10;

    UIFont *lfont = [UIFont boldSystemFontOfSize:kUIFontSize01];
    CGFloat nheight = [CommonUtil getSizeFromString:desc font:lfont width:width].height;
    nheight = nheight < 19 ? 19.0f : fabs(nheight) + 1.0f; //adjust padding
    return nheight;
}

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

    NSDictionary *homeDic = _dataArray[indexPath.section];
    HomeLogModel *homelog = homeDic[@"list"][indexPath.row];
    CGFloat height = 0.0f;
    if ([homelog.homelogType isEqualToString:@"RL"]) {//규칙 실행 로그
        CGFloat theight = [self calculateTitleHeight:homelog.homelogTitle];
        CGFloat dheight = [self calculateDescHeight:homelog.homelogMsg];
        height = 34.0f + theight + dheight; //(title.height + padding)

    } else if ([homelog.homelogType isEqualToString:@"DV"]) {//디바이스 실행 로그
        CGFloat theight = [self calculateTitleHeight:homelog.homelogTitle];
        CGFloat dheight = [self calculateDescHeight:homelog.homelogMsg];
        height = 34.0f + theight + dheight; //(title.height + padding)

    } else if ([homelog.homelogType isEqualToString:@"MC"]) {//멀티 실행 로그
        CGFloat theight = [self calculateTitleHeight:homelog.homelogTitle];
        CGFloat dheight = [self calculateDescHeight:homelog.homelogMsg];
        height = 34.0f + theight + dheight; //(title.height + padding)

    } else if ([homelog.homelogType isEqualToString:@"HM"]) {//멤버 로그
        CGFloat theight = [self calculateTitleHeight:homelog.homelogTitle];
        height = 80.0f + theight;

    } else if ([homelog.homelogType isEqualToString:@"HO"]) {//홈 로그
        CGFloat theight = [self calculateTitleHeight:homelog.homelogTitle];
        height = 80.0f + theight;

    }

    return height;
}

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

    UITableViewCell *cell = nil;
    NSDictionary *homeDic = _dataArray[indexPath.section];
    HomeLogModel *homelog = homeDic[@"list"][indexPath.row];

    if ([homelog.homelogType isEqualToString:@"RL"]) {//규칙 실행 로그
        HomeLogsRuleTableViewCell *rcell = (HomeLogsRuleTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"HomeLogsRuleCellIdentifier"];
        rcell.lblTime.text = homelog.createTime;
        rcell.lblTitle.text = homelog.homelogTitle;
        rcell.lblRule.text = homelog.homelogMsg;
        [rcell.imgvIcon setImage:[UIImage imageNamed:@"tp_01_img_homelog_icon_rule"]];

        cell = rcell;

    } else if ([homelog.homelogType isEqualToString:@"DV"]) {//디바이스 실행 로그
        HomeLogsRuleTableViewCell *rcell = (HomeLogsRuleTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"HomeLogsRuleCellIdentifier"];
        rcell.lblTime.text = homelog.createTime;
        rcell.lblTitle.text = homelog.homelogTitle;
        rcell.lblRule.text = homelog.homelogMsg;
        [rcell.imgvIcon setImage:[UIImage imageNamed:@"tp_01_img_homelog_icon_rule"]];

        cell = rcell;

    } else if ([homelog.homelogType isEqualToString:@"MC"]) {//멀티제어 실행 로그
        HomeLogsRuleTableViewCell *rcell = (HomeLogsRuleTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"HomeLogsRuleCellIdentifier"];
        rcell.lblTime.text = homelog.createTime;
        rcell.lblTitle.text = homelog.homelogTitle;
        rcell.lblRule.text = homelog.homelogMsg;
        [rcell.imgvIcon setImage:[UIImage imageNamed:@"tp_01_img_homelog_icon_rule"]];

        cell = rcell;

    } else if ([homelog.homelogType isEqualToString:@"HM"]) {//멤버 로그
        HomeLogsMemberTableViewCell *rcell = (HomeLogsMemberTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"HomeLogsMemberCellIdentifier"];
        rcell.lblTime.text = homelog.createTime;
        rcell.lblTitle.text = homelog.homelogTitle;
        rcell.lblMemberRole.text = homelog.homelogMsg; //log[@"member_role"];
//        rcell.lblMemberName.text = log[@"member_name"];
        [rcell.imgvIcon setImage:[UIImage imageNamed:@"tp_01_img_homelog_icon_member"]];
        [rcell.imgvMemberIcon sd_setImageWithURL:[NSURL URLWithString:homelog.imageFileName] forState:UIControlStateNormal];

        cell = rcell;

    } else if ([homelog.homelogType isEqualToString:@"HO"]) {//홈 실행 로그
        HomeLogsHomeTableViewCell *rcell = (HomeLogsHomeTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"HomeLogsHomeCellIdentifier"];
        rcell.lblTime.text = homelog.createTime;
        rcell.lblTitle.text = homelog.homelogTitle;
        rcell.lblMemberRole.text = homelog.homelogMsg; //log[@"member_role"];
        [rcell.imgvIcon setImage:[UIImage imageNamed:@"tp_01_img_homelog_icon_home"]];
//        rcell.lblMemberName.text = log[@"member_name"];

        [rcell.imgvMemberIcon sd_setImageWithURL:[NSURL URLWithString:homelog.imageFileName] forState:UIControlStateNormal];

        cell = rcell;
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath 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
