//
//  VankeNoticeListModel.m
//  vanke
//
//  Created by xiaomi on 15/10/8.
//  Copyright © 2015年 gomore. All rights reserved.
//

#import "VankeNoticeListModel.h"
#import "VankeNoticeListAPI.h"

#undef	PER_PAGE
#define PER_PAGE	(30)

@implementation VankeNoticeListModel

@synthesize notices = _notices;
@synthesize read = _read;

- (void)load
{
    self.autoSave = YES;
    self.autoLoad = YES;
    self.notices = [NSMutableArray array];
}

- (void)unload
{
    self.notices = nil;
}

#pragma mark - paging query

- (void)firstPage
{
    [self gotoPage:1];
}

- (void)nextPage
{
    if ( self.notices.count )
    {
        [self gotoPage:(self.notices.count / PER_PAGE + 1)];
    }
}

- (void)gotoPage:(NSUInteger)page {
    [VankeNoticeListAPI cancel];
    
    VankeNoticeListAPI *api = [VankeNoticeListAPI api];
    
    @weakify(api);
    @weakify(self);
    
    api.read = self.read;
    api.pageNumber = page - 1;
    api.pageSize = PER_PAGE;
    
    api.whenUpdate = ^
    {
        @normalize(api);
        @normalize(self);
        
        if ( api.sending )
        {
            [self sendUISignal:self.RELOADING];
        }
        else
        {
            if ( api.succeed )
            {
                NoticeListResponse *resp = (NoticeListResponse*) api.serverResp;
                if ( nil == resp || nil == resp.data )
                {
                    api.failed = YES;
                }
                else
                {
                    NSMutableArray *notices = (NSMutableArray*) self.notices;
                    if ( page <= 1 )
                    {
                        [notices removeAllObjects];
                        [notices addObjectsFromArray:resp.data.records];
                    }
                    else
                    {
                        [notices addObjectsFromArray:resp.data.records];
                        [notices unique:^NSComparisonResult(id left, id right) {
                            return [((Notice *)left).uuid compare:((Notice *)right).uuid];
                        }];
                    }
                    
                    self.more = (self.notices.count >= [resp total]) ? NO : YES;
                    self.loaded = YES;
                }
            }
                        
            [self sendUISignal:self.RELOADED];
        }
    };
    
    [api send];
}

@end
