//
//  FaqViewController.m
//  OneCable
//
//  Created by nComz on 2017. 4. 4..
//  Copyright © 2017년 ntels. All rights reserved.
//

#import "FaqViewController.h"
#import "CustomTableView.h"
#import "CustomImageView.h"
#import "JYRefreshController.h"
#import "RequestHandler.h"
#import "FaqDetailViewController.h"

@implementation FaqTableViewCell

@end

@interface FaqViewController () {
    NSMutableArray<FaqModel> *_faqList;
    NSString *_pagingId, *_pagingType;
    NSDate *_prevReadTime;
}

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

@end

@implementation FaqViewController


- (void)viewDidLoad {
    [super viewDidLoad];

    _faqList = [(NSMutableArray<FaqModel> *)[NSMutableArray alloc] init];
    [self initUI];
    [self prepareViewDidLoad];

}

- (void)initUI {
    
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    statusBar.backgroundColor = [UIColor whiteColor];
    
    [self.navigationController.navigationBar setHidden:YES];
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    
    [self initTableViewAsDefaultStyle:_tableView];
    
    _noContentView.hidden = NO;
    _tableView.hidden = YES;
    
    [self initRefreshController];
}

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

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

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

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

- (void)requestFaqListRecently {
    FaqModel *faq = [_faqList firstObject];
    _pagingType = ksListPagingTypeUpward;
    _pagingId = faq.faqId;
    
    [self performSelector:@selector(requestFaqList) withObject:nil afterDelay:0.0f];
}

- (void)requestFaqListOlder {
    FaqModel *faq = [_faqList lastObject];
    _pagingType = ksListPagingTypeDownward;
    _pagingId = faq.faqId;
    
    [self performSelector:@selector(requestFaqList) withObject:nil afterDelay:0.0f];
}

- (void)requestFaqList{

//    NSDictionary *parameter = @{@"member_id":[JDFacade facade].loginUser.memberId,
//                                @"faq_id": _pagingId ? _pagingId : ksEmptyString,
//                                @"paging_type": _pagingType ? _pagingType : ksEmptyString,
//                                @"read_datetime": [JDFacade facade].loginUser.noticeReadTime ? [JDFacade facade].loginUser.noticeReadTime : ksEmptyString};
    
    NSDictionary *parameter = @{@"faq_id": _pagingId ? _pagingId : ksEmptyString,
                                @"paging_type" : ksEmptyString,
                                @"read_datetime" :  ksEmptyString};
    
    NSString *path = API_GET_FAQ;
//    NSString *path = [[JDFacade facade] getUrlWithCustAndGroupID:API_GET_FAQ arguments:nil];

    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[FaqListModel class] completion:^(id responseObject) {
        
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        
        NSLog(@"FAQ List : %@", responseObject);
        
        FaqListModel *fetchedFaqList = (FaqListModel *) responseObject;
        
        if (fetchedFaqList && fetchedFaqList.faqList && fetchedFaqList.faqList.count) { // API 성공
            
//            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:0];

            if (_pagingType && [_pagingType isEqualToString:ksListPagingTypeUpward]) {
//                [_faqList insertObjects:fetchedFaqList.faqList atIndexes:indexSet];
            } else {
                [_faqList addObjectsFromArray:fetchedFaqList.faqList];
            }
            
            //테이블 컨텐츠가 없을 경우,
            if (_tableView.hidden) {
//                [_mainView bringSubviewToFront:_tableView];
                _noContentView.hidden = YES;
                _tableView.hidden = NO;
            }
            
            [_tableView reloadData];
            
        } else {
            if (!_faqList.count) {  //이미 로드된 데이터가 있을 경우는 출력하지 않음.
//                [_mainView bringSubviewToFront:_noContentView];
                _noContentView.hidden = NO;
                _tableView.hidden = YES;
            }
        }
        
        //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 {

    return UITableViewAutomaticDimension;
}

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

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

    return _faqList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    FaqModel *faq = _faqList[indexPath.row];
    
    FaqTableViewCell *cell = (FaqTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"FaqCellIdentifier"];
    
    
    cell.lblCount.text = [NSString stringWithFormat:@"%lu%@",(_faqList.count - indexPath.row),@"."];
    cell.lblContent.text = faq.title;
    //cell.lblDate.text = [CommonUtil formattedDate4:faq.createDatetime];
    
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    FaqModel *faq = _faqList[indexPath.row];
    FaqDetailViewController *vc =[CommonUtil instantiateViewControllerWithIdentifier:@"FaqDetailViewController" storyboardName:@"Main"];
    
    NSString *detail_count =[NSString stringWithFormat:@"%lu",(_faqList.count - indexPath.row)];
    
//    vc.detail_Url = select_faq.detailUrl;
//    _detailUrl = select_faq.detailUrl;

    vc.faqModel = faq;
    vc.detail_count = detail_count;
    
    [self.navigationController pushViewController:vc animated:YES];
    
}

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

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
