//
//  MessageBoxViewController.m
//  kneet2
//
//  Created by Jason Lee on 10/14/15.
//  Copyright © 2015 ntels. All rights reserved.
//

#import "MessageBoxViewController.h"
#import "RequestHandler.h"
#import "ModeModel.h"

#import "CustomTableView.h"
#import "CustomLabel.h"
#import "CustomButton.h"
#import "CustomImageView.h"

#import "JYRefreshController.h"

@implementation MessageBoxTableViewCell

@end

@interface MessageBoxViewController () <UITableViewDataSource, UITableViewDelegate> {
    NSMutableArray<PersonalNoticeModel> *_personalNoticeList;
    NSString *_pagingId, *_pagingType;
    NSDate *_prevReadTime;
}

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

@end


#pragma mark - Class Definition

@implementation MessageBoxViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
 
    _personalNoticeList = (NSMutableArray<PersonalNoticeModel> *)[[NSMutableArray alloc] init];
    
    [self initUI];
//    [self prepareViewDidLoad];
}


- (void)initUI {
    [self initTableViewAsDefaultStyle:_tableView];
    
    _noContentView.hidden = NO;
    _tableView.hidden = YES;
//    _tableView.estimatedRowHeight = 169.0f; // set to whatever your "average" cell height is
//    _tableView.rowHeight = UITableViewAutomaticDimension;
    [self initRefreshController];
}

- (void)initRefreshController {
    //set refresh controls
    __weak typeof(self) weakSelf = self;

    self.refreshController = [[JYPullToRefreshController alloc] initWithScrollView:self.tableView];
    self.refreshController.pullToRefreshHandleAction = ^{
        [weakSelf requestPersonalNoticesRecently];
    };
    
    self.loadMoreController = [[JYPullToLoadMoreController alloc] initWithScrollView:self.tableView];
    self.loadMoreController.enable = NO;
    
    self.loadMoreController.pullToLoadMoreHandleAction = ^{
        [weakSelf requestPersonalNoticesOlder];
    };
}

- (void)stopRefreshController {
    
    if (self.refreshController && self.refreshController.refreshState == JYRefreshStateLoading) {
        [self.refreshController stopRefreshWithAnimated:YES completion:nil];
    }
    
    if (self.loadMoreController) {
        [self.loadMoreController stopLoadMoreCompletion:nil];
        self.loadMoreController.enable = _personalNoticeList.count % kdListPagginSize == 0;
    }
}

- (void)prepareViewDidLoad {
//    [self requestPersonalNotices];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [_personalNoticeList removeAllObjects];
    [self requestPersonalNotices];
}

#pragma mark - Main Logic

- (void)requestPersonalNoticesRecently {
    
    PersonalNoticeModel *notice = [_personalNoticeList firstObject];
    _pagingType = ksListPagingTypeUpward;
    _pagingId = notice.pushHistId;
    
    [self performSelector:@selector(requestPersonalNotices) withObject:nil afterDelay:0.0f];
}

- (void)requestPersonalNoticesOlder {
    PersonalNoticeModel *notice = [_personalNoticeList lastObject];
    _pagingType = ksListPagingTypeDownward;
    _pagingId = notice.pushHistId;
    
    [self performSelector:@selector(requestPersonalNotices) withObject:nil afterDelay:0.0f];
}

- (void)requestPersonalNotices {
    //parameters
//    NSDictionary *parameter = @{@"member_id" : [JDFacade facade].loginUser.emailId,
//                                @"message_id": _pagingId ? _pagingId : ksEmptyString,
//                                @"paging_type": _pagingType ? _pagingType : ksEmptyString,
//                                @"read_datetime": [JDFacade facade].loginUser.personalNoticeReadTime ? [JDFacade facade].loginUser.personalNoticeReadTime : ksEmptyString};
    
    NSDictionary *parameter = @{@"member_id" : [JDFacade facade].loginUser.memberId,
                                @"create_datetime": ksEmptyString,
                                @"paging_type" : ksEmptyString,
                                @"read_datetime":  ksEmptyString};
    
//    NSString *path = API_GET_NOTICE_PERSONAL;
    NSString *path = [[JDFacade facade] getUrlWithCustAndGroupID:API_GET_NOTICE_PERSONAL arguments:nil];
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[PersonalNoticeListModel class] completion:^(id responseObject) {
        
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }

        PersonalNoticeListModel *fetchedPersonalNoticeList = (PersonalNoticeListModel *) responseObject;
        
        if (fetchedPersonalNoticeList && fetchedPersonalNoticeList.messageList &&
            fetchedPersonalNoticeList.messageList.count) {//API 성공 ,

//            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:0];
            
            if (_pagingType && [_pagingType isEqualToString:ksListPagingTypeUpward]) {
//                [_personalNoticeList insertObjects:fetchedPersonalNoticeList.messageList atIndexes:indexSet];
            } else {
                [_personalNoticeList addObjectsFromArray:fetchedPersonalNoticeList.messageList];
            }

            //테이블 컨텐츠가 없을 경우,
            if (_tableView.hidden) {
//                [_mainView bringSubviewToFront:_tableView];
                _noContentView.hidden = YES;
                _tableView.hidden = NO;
            }
            
//            [self initRefreshController];
            [_tableView reloadData];
            
        } else {
            if (!_personalNoticeList.count) {//이미 로드된 데이터가 있을 경우는 출력하지 않음.
                
//                [_mainView bringSubviewToFront:_noContentView];
                _noContentView.hidden = NO;
                _tableView.hidden = YES;
            }
        }
        
        if (_personalNoticeList && _personalNoticeList.count > 0) {
            _prevReadTime = [JDFacade facade].loginUser.personalNoticeReadTime ? [CommonUtil dateFromDateString:[JDFacade facade].loginUser.personalNoticeReadTime] : nil;
            
            //set notice title
            PersonalNoticeModel *notice = _personalNoticeList[0];
            if (![JDFacade facade].loginUser.personalNoticeReadTime || ![[JDFacade facade].loginUser.personalNoticeReadTime isEqualToString:notice.createDatetime]) {//기존 읽은 날짜랑 틀린 경우,
                [JDFacade facade].loginUser.personalNoticeReadTime = notice.createDatetime;
            }
            
//            _lblTitle.text = [NSString stringWithFormat:@"메시지 박스 %@", fetchedPersonalNoticeList.pushCount];
//            [_lblTitle setColor:kUITextColor02 text:fetchedPersonalNoticeList.pushCount];            
        }
        
        //refresh controller
        [self stopRefreshController];
        
        
    } failure:^(id errorObject) {
        
        [self stopRefreshController];
        
        JDErrorModel *error = (JDErrorModel *)errorObject;
        if (error != nil) [[JDFacade facade] alert:error.errorMessage];
        
    }];
}

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

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

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    //    CGFloat height = 0.0f;
    //
    //    if (indexPath.section == 0) {
    //        height = 81.0f;
    //    }
    
    return UITableViewAutomaticDimension;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = nil;
    
    PersonalNoticeModel *notice = _personalNoticeList[indexPath.row];

//    if (notice) {
        MessageBoxTableViewCell *tcell = (MessageBoxTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"PersonalNoticeCellIdentifier"];
     
        BOOL isNew = [[CommonUtil dateFromDateString:notice.createDatetime] isLaterThanDate:_prevReadTime];
    
      tcell.imgvStatus.image = isNew ? [UIImage imageNamed:@"common_bg_list_03"] : [UIImage imageNamed:@"common_bg_list_01"];
        
//        NSArray *contents = [notice.content componentsSeparatedByString:@"\n"];
//        NSLog(@"%s\n %@\n%@", __PRETTY_FUNCTION__, notice.content, contents);
    
//        tcell.lblContent.text = contents && contents.count > 1 ? contents[0] : notice.content;
        tcell.lblContent.text = notice.content;
        tcell.lblReadDatatime.text = [CommonUtil formattedDate4:notice.createDatetime];
    
//        //초기화
//        tcell.containerView.hidden = tcell.lblSubContent.hidden = tcell.btnSubContent.hidden = NO;
//        tcell.constraintImgvClockTop.constant = 72;
    
//        if ([notice.pushTypeCode isEqualToString:@"HOME_MEM_INV"]) {//초대 관련
//            tcell.lblSubContent.hidden = YES;
//            tcell.btnSubContent.enabled = [notice.homegrpInvitationYn boolValue];
//            
//        } else {
//            if (contents && contents.count > 1) {
//                tcell.btnSubContent.hidden = YES;
//                tcell.lblSubContent.text = contents[1];
//                
//            } else {
//                tcell.containerView.hidden = YES;
//                tcell.lblSubContent.hidden = YES;
//                tcell.btnSubContent.hidden = YES;
//                
////                tcell.constraintImgvClockTop.constant = 20;
//            }
//        }
    
//        tcell.btnSubContent.value = notice;
//        
//        if (![tcell.btnSubContent actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
//            [tcell.btnSubContent addTarget:self action:@selector(btnSubContentTouched:) forControlEvents:UIControlEventTouchUpInside];
//        }
    
        cell = tcell;
//    }
    
    return cell;
}

//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    [super tableView:tableView didSelectRowAtIndexPath:indexPath];
//}

//- (void)btnSubContentTouched:(id)sender {
//    [[JDFacade facade] loadInvitationView];
//}

#pragma mark - UI Events
- (IBAction)btnCloseTouched:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}


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



@end
