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

#import "VankeStatementSubjectListModel.h"

#undef	PAGE_SIZE
#define PAGE_SIZE	(20)

@implementation VankeStatementSubjectListModel

@synthesize settle = _settle;
@synthesize contract = _contract;
@synthesize items = _items;
@synthesize lastResp = _lastResp;

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

- (void)unload
{
    self.settle = nil;
    self.contract = nil;
    self.items = nil;
}

#pragma mark - paging query

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

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

- (void)gotoPage:(NSUInteger)page {
    [VankeSettlementSubjectListAPI cancel];
    
    VankeSettlementSubjectListAPI *api = [VankeSettlementSubjectListAPI api];
    
    @weakify(api);
    @weakify(self);
    
    api.settle = self.settle;
    api.contract = self.contract;
    
    api.whenUpdate = ^
    {
        @normalize(api);
        @normalize(self);
        
        if ( api.sending )
        {
            [self sendUISignal:self.RELOADING];
        }
        else
        {
            if ( api.succeed )
            {
                StatementSubjectListResponse *resp = (StatementSubjectListResponse*) api.serverResp;
                self.lastResp = resp;
                if ( nil == resp || nil == resp.data || nil == resp.data.items )
                {
                    api.failed = YES;
                }
                else
                {
                    if ( page <= 1 )
                    {
                        [self.items removeAllObjects];
                        [self.items addObjectsFromArray:resp.data.items];
                    }
                    else
                    {
                        [self.items addObjectsFromArray:resp.data.items];
                        [self.items unique:^NSComparisonResult(id left, id right) {
                            return [((SubjectItem*)left).subject compare:((SubjectItem*)right).subject];
                        }];
                    }
                    
                    self.more = NO;
                    self.loaded = YES;
                }
            }
                        
            [self sendUISignal:self.RELOADED];
        }
    };
    
    [api send];
}

@end
