//
//  WMListViewModel.m
//  Gengmei
//
//  Created by Thierry on 3/5/15.
//  Copyright (c) 2015 Wanmeichuangyi. All rights reserved.
//

#import "WMFetchDataViewModel.h"

@implementation WMFetchDataViewModel
{
    
}
- (instancetype)init{
    self = [super init];
    if (self) {
        _remoteUrl = @"";
        
        _dataArray = [[NSMutableArray alloc] init];
        _startNum = 0;
        _params = nil;
        _count = 10;
        _deduplicationDic = [NSMutableDictionary dictionary];
        _fetchDataErrorMsg = @"获取数据失败，请重试";
        _fetchDataNilMsg = @"暂时没有相关数据";
        _message = @"";
        //方便 某个接口做其他请求方式 上传需求
        _httpMethod = HttpMethodGet;
    }
    return self;
}

/**
 *  @brief  默认列表对于的接口都会有start_num和count参数
 *          如果没有则重写此方法即可
 */
- (void)buildParams{
    _params = @{@"start_num":@(self.startNum),
                @"count":@(self.count)};
}

- (BOOL)shouldClearDataForResponse:(id)response{
    return self.startNum == 0;
}

- (void)fetchRemoteData{
    
    if (_remoteUrl.length == 0) {
        return;
    }
    
    if (_httpMethod == nil) {
        //防止某种情况下为空 加一个默认值
        _httpMethod = HttpMethodGet;
    }
    
    [self buildParams];
    [[WMNetService sharedInstance] sendRequestWithURLString:_remoteUrl parameters:_params method:_httpMethod success:^(id responseObject) {
        if ([self shouldClearDataForResponse:responseObject]) {
            [self clearData];
        }
    
        //某些接口返回的直接是数组
        if ([responseObject isKindOfClass:[NSArray class]]) {
            
            NSArray *array = (NSArray *)responseObject;
            [self buildModelWithRemoteArray:array];
            [self setValue:@YES forKey:@"fetchDataSuccess"];
        }else if([responseObject isKindOfClass:[NSDictionary class]]){
           
            NSDictionary *dic = (NSDictionary *)responseObject;
            NSInteger code = [[dic objectForKey:@"error"] integerValue];
            self.message = responseObject[@"message"];
            if (code == APIStatusCodeSuccess) {
                [self buildModelWithRemoteDic:dic];
                [self setValue:@YES forKey:@"fetchDataSuccess"];
                
            }else if (code == APIStatusCodeEmpty){
                self.message = responseObject[@"message"];
                [self setValue:@YES forKey:@"fetchDataSuccess"];
                
            }else{
                [self setValue:@NO forKey:@"fetchDataSuccess"];
            }
        }
        
    } failed:^(NSString *errorMsg) {
        [self setValue:@NO forKey:@"fetchDataSuccess"];
    }];
}


/**
 *  @author wangyang, 15-11-25 16:11:00
 *
 *  @brief  在确认需要被清除数据时才调用。刷新开始并不代码需要清除数据
 */
- (void)clearData{
    // 因为 clearData 可能会被外部调用，所以 self.startNum = 0 要确认执行，不能少
    self.startNum = 0;
    _deleteCount = 0;
    [self.dataArray removeAllObjects];
    [_deduplicationDic removeAllObjects];
}

- (void)handleHeaderRefreshing
{
    self.startNum = 0;
    [self fetchRemoteData];
}

- (void)handleFooterRereshing
{
    self.startNum = self.dataArray.count + _deleteCount;
    [self fetchRemoteData];
}

/**

 */
- (void)buildModelWithRemoteDic:(NSDictionary *)dic{
    
}

/**
 *  @brief 空方法，由子类来实现
 *
 *  @param dic  返回的数组型数据
 */
- (void)buildModelWithRemoteArray:(NSArray *)array{

}


- (void)deduplicationForArray:(NSArray *)array buildModelBlock:(id (^)(NSDictionary *dic))buildBlock{

    if (_deduplicationKey.length == 0) {
        return;
    }

    // NSMutableArray 不是线程安全的，不能使用并行枚举。参考https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html
    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        id value = [obj valueForKey:_deduplicationKey];
        NSString *key = [value isKindOfClass:[NSString class]] ? value : [value stringValue];
        NSAssert(key.length > 0, @"key 怎么会是一个空???!!!");
        if (!_deduplicationDic[key]) {
            if ([obj isKindOfClass:[NSDictionary class]]) {
                id object = buildBlock(obj);
                [self.dataArray addObject:object];
            }else{
                [self.dataArray addObject:obj];
            }
            _deduplicationDic[key] = @1;
        }else{
            _deleteCount ++;
        }
    }];
}

- (NSArray *)deduplicationArrayFromArray:(NSArray *)array buildModelBlock:(id (^)(NSDictionary *dic))buildBlock{

    if (_deduplicationKey.length == 0) {
        return @[];
    }

    NSMutableArray *result = [NSMutableArray array];

    // NSMutableArray 不是线程安全的，不能使用并行枚举。参考https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html
    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([self.notDeduplicate containsObject:obj[@"type"]]) {
            id object = buildBlock(obj);
            [result addObject:object];
        } else {
            id value = [obj valueForKey:_deduplicationKey];
            NSString *key = [value isKindOfClass:[NSString class]] ? value : [value stringValue];
            NSAssert(key.length > 0, @"key 怎么会是一个空???!!!");
            if (!_deduplicationDic[key]) {
                if ([obj isKindOfClass:[NSDictionary class]]) {
                    id object = buildBlock(obj);
                    [result addObject:object];
                }else{
                    [result addObject:obj];
                }
                _deduplicationDic[key] = @1;
            }else{
                self.deleteCount ++;
            }
        }
    }];

    return result;
}


@end
