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

#import "RequestHandler.h"
#import "CustomTableView.h"

#import "JYRefreshController.h"
#import "NoticeViewController.h"
#import "CustomImageView.h"

@implementation NoticeTableViewCell

@end

@interface NoticeViewController () {
    NSMutableArray<NoticeModel> *_noticeList;
    NSString *_pagingId, *_pagingType;
    NSDate *_prevReadTime;
}

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

@end


#pragma mark - Class Definition

@implementation NoticeViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _noticeList = [(NSMutableArray<NoticeModel> *)[NSMutableArray alloc] init];

    [self initUI];
    [self prepareViewDidLoad];
}

- (void)initUI {
    
    [self initTableViewAsDefaultStyle:_tableView];
    
    _noContentView.hidden = NO;
    _tableView.hidden = YES;
//    _tableView.estimatedRowHeight = 117.0; // 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 requestNoticeListRecently];
    };
  
    self.loadMoreController = [[JYPullToLoadMoreController alloc] initWithScrollView:self.tableView];
    self.loadMoreController.enable = NO;
    
    self.loadMoreController.pullToLoadMoreHandleAction = ^{
        [weakSelf requestNoticeListOlder];
    };
    
}

- (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 = _noticeList.count % kdListPagginSize == 0;
    }
}

- (void)prepareViewDidLoad {
    [self requestNoticeList];
}

#pragma mark - Main Logic

- (void)requestNoticeListRecently {
    NoticeModel *notice = [_noticeList firstObject];
    _pagingType = ksListPagingTypeUpward;
    _pagingId = notice.noticeId;
    
    [self performSelector:@selector(requestNoticeList) withObject:nil afterDelay:0.0f];
}

- (void)requestNoticeListOlder {
    NoticeModel *notice = [_noticeList lastObject];
    _pagingType = ksListPagingTypeDownward;
    _pagingId = notice.noticeId;
    
    [self performSelector:@selector(requestNoticeList) withObject:nil afterDelay:0.0f];
}

- (void)requestNoticeList {
    //parameters
//    NSDictionary *parameter = @{@"member_id":[JDFacade facade].loginUser.memberId,
//                                @"notice_id" : _pagingId ? _pagingId : ksEmptyString,
//                                @"paging_type" : _pagingType ? _pagingType : ksEmptyString,
//                                @"read_datetime": [JDFacade facade].loginUser.noticeReadTime ? [JDFacade facade].loginUser.noticeReadTime : ksEmptyString };

    NSDictionary *parameter = @{@"member_id":[JDFacade facade].loginUser.memberId,
                                @"notice_id" : _pagingId ? _pagingId : ksEmptyString,
                                @"paging_type" : ksEmptyString,
                                @"read_datetime" :  ksEmptyString };
    
//    NSString *path = [NSString stringWithFormat:API_GET_NOTICE];
    NSString *path = [[JDFacade facade] getUrlWithCustAndGroupID:API_GET_NOTICE arguments:nil];
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[NoticeListModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        NSLog(@"Notice List : %@", responseObject);

        NoticeListModel *fetchedNoticeList = (NoticeListModel *) responseObject;
        
        if (fetchedNoticeList && fetchedNoticeList.noticeList &&
            fetchedNoticeList.noticeList.count) { //API 성공 ,
            
//            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:0];

            if (_pagingType && [_pagingType isEqualToString:ksListPagingTypeUpward]) {
//                [_noticeList insertObjects:fetchedNoticeList.noticeList atIndexes:indexSet];
            } else {
            [_noticeList addObjectsFromArray:fetchedNoticeList.noticeList];

            }

            //테이블 컨텐츠가 없을 경우,
            if (_tableView.hidden) {
//                [_mainView bringSubviewToFront:_tableView];
                _noContentView.hidden = YES;
                _tableView.hidden = NO;
            }
            
//            [self initRefreshController];
            [_tableView reloadData];
            
        } else {
            if (!_noticeList.count) {//이미 로드된 데이터가 있을 경우는 출력하지 않음.
                
//                [_mainView bringSubviewToFront:_noContentView];
                _noContentView.hidden = NO;
                _tableView.hidden = YES;
            }
        }
        
        _prevReadTime = [JDFacade facade].loginUser.noticeReadTime ? [CommonUtil dateFromDateString:[JDFacade facade].loginUser.noticeReadTime] : nil;
        
        //set notice title
        if (_noticeList && _noticeList.count > 0) {
            NoticeModel *notice = _noticeList[0];
            if (![JDFacade facade].loginUser.noticeReadTime || ![[JDFacade facade].loginUser.noticeReadTime isEqualToString:notice.createDatetime]) {//기존 읽은 날짜랑 틀린 경우,
                [JDFacade facade].loginUser.noticeReadTime = notice.createDatetime;
            }
            
//            _lblTitle.text = [NSString stringWithFormat:@"공지사항 %@", fetchedNoticeList.noticeCount];
//            [_lblTitle setColor:kUITextColor02 text:fetchedNoticeList.noticeCount];
        }
        
        //refresh control
        [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;
}

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

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NoticeModel *notice = _noticeList[indexPath.row];
    
    NSLog(@"Notice List : %@ : ",notice);
    NoticeTableViewCell *cell = (NoticeTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"NoticeCellIdentifier"];
    
    BOOL isNew = [[CommonUtil dateFromDateString:notice.createDatetime] isLaterThanDate:_prevReadTime];
    cell.imgvStatus.image = isNew ? [UIImage imageNamed:@"common_bg_list_03"] : [UIImage imageNamed:@"common_bg_list_01"];

    cell.lblCount.text = [NSString stringWithFormat:@"%lu%@",(_noticeList.count - indexPath.row),@"."];
    cell.lblContent.text = notice.content;
    cell.lblCreateDatetime.text = [CommonUtil formattedDate3:notice.createDatetime];
    
    return cell;
}


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


#pragma mark - MemoryWarning
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end
