//
//  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"

@implementation NoticeTableViewCell

@end

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

@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];
    
    //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.pullToLoadMoreHandleAction = ^{
        [weakSelf requestNoticeListOlder];
    };
}

- (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 = @{@"notice_id" : _pagingId ? _pagingId : ksEmptyString,
                                @"paging_type" : _pagingType ? _pagingType : ksEmptyString,
                                @"read_datetime": [JDFacade facade].loginUser.noticeReadTime ? [JDFacade facade].loginUser.noticeReadTime : ksEmptyString };
    
    NSString *path = [NSString stringWithFormat:API_GET_NOTICE];
    
    [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:parameter modelClass:[NoticeListModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        
        NoticeListModel *fetchedNoticeList = (NoticeListModel *) responseObject;
        
        if (fetchedNoticeList && fetchedNoticeList.noticeList &&
            fetchedNoticeList.noticeList.count) {//API 성공 ,
            [_noticeList addObjectsFromArray:fetchedNoticeList.noticeList];
            
            //set notice title
            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];
            
        } else {
        }
        
        [self.refreshController stopRefreshWithAnimated:YES completion:nil];
        [self.loadMoreController stopLoadMoreCompletion:nil];
        self.loadMoreController.enable = _noticeList.count % 20 == 0;
        
        [_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 _noticeList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 120;
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NoticeModel *notice = _noticeList[indexPath.row];
    
    NoticeTableViewCell *cell = (NoticeTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"NoticeCellIdentifier"];
    
    cell.lblContent.text = notice.content;
    cell.lblCreateDatetime.text = [CommonUtil formattedDate3:notice.createDatetime];
    
    return cell;
}

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


#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