//
//  ALFaceFittingAPI.m
//  GMAlpha
//
//  Created by Jing on 2018/11/28.
//  Copyright © 2018 Gengmei. All rights reserved.
//

#import "ALFaceFittingAPI.h"
#import "ALFaceStarModel.h"
#import "ALDownloadManager.h"
#import "ALUploadManager.h"
#import "FileUtils.h"
#import "ALScanManager.h"

@implementation ALFaceFittingAPI

#define ALSTAR_FITTING_FINISH_OBJ_LIST    @"ALStarFittingFinishObjList"
#define ALSTAR_FITTING_FINISH_UV_LIST     @"ALStarFittingFinishUvList"
#define ALSTAR_FITTING_DOWNLOADING_LIST   @"ALStarFittingDownloadingList"

static NSURLSessionDownloadTask *_downloadTask;

static dispatch_queue_t url_finish_list_creation_queue() {
    static dispatch_queue_t url_finish_list_creation_queue;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        url_finish_list_creation_queue = dispatch_queue_create("url_finish_list_creation_queue", DISPATCH_QUEUE_SERIAL);
    });
    
    return url_finish_list_creation_queue;
}

+ (void)fetchFaceFittingDataWithCompletion:(nullable void (^)(GMResponseOC *))completion {
    [GMNetworking requestOCWithApi:API_FACE_FITTING method:GMHTTPMethodGet parameters:nil completion:^(GMResponseOC * _Nonnull responseObject) {
        if (responseObject.isSuccess) {
            NSDictionary *dataDict = (NSDictionary *)responseObject.data;
            NSString *nid = dataDict[@"id"];
            if ([nid isNonEmpty]) {
                //单独存储fittingId 存储user 信息下有时候会为空
                if (ALScanManager.shareInstance.fittingId) ALScanManager.shareInstance.fittingTempId = nid;
                else ALScanManager.shareInstance.fittingId = nid;
                if (completion) completion(responseObject);
            }
        } else {
            if (completion) {
                completion(responseObject);
            };
//            if (![GMLoginManager shareInstance].isVisitor) [self fetchFaceFittingDataWithCompletion:completion];
        }
    }];
}

+ (void)fetchStarListWithParameters:(NSDictionary *)parameters completion:(nullable void (^)(GMResponseOC *))completion {
    [GMNetworking requestOCWithApi:API_FACE_RESULT method:GMHTTPMethodGet parameters:parameters completion:^(GMResponseOC * _Nonnull responseObject) {
        if (completion) completion(responseObject);
        if (responseObject.isSuccess) {
            NSDictionary *stars = responseObject.data[@"stars"];
            if (stars) {
                NSArray *maleStar = stars[@"male"];
                NSArray *femaleStar = stars[@"female"];
                NSArray <ALFaceStarModel *>*maleStarList = [ALFaceStarModel arrayOfModelsFromDictionaries:maleStar error:nil];
                NSArray <ALFaceStarModel *>*femaleStarList = [ALFaceStarModel arrayOfModelsFromDictionaries:femaleStar error:nil];
                NSMutableArray *starList = [NSMutableArray arrayWithArray:femaleStarList];
                [starList addObjectsFromArray:maleStarList];
                [GMCache storeObjectAtMemoryWithkey:ALMALE_STAR_FITTING_LIST object:maleStarList];
                [GMCache storeObjectAtMemoryWithkey: ALFEMALE_STAR_FITTING_LIST object:femaleStarList];
               
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    NSInteger index = 0;
                    BOOL lock = NO;
                    while (index < starList.count && !lock) {
                        ALFaceStarModel *star = starList[index];
                        lock = star.isLock;
                        index++;
                        if (star.starModelUrl) [self fetchStarFittingObjWithUrl:star.starModelUrl starId:star.id];
                        if (star.starUv) [self fetchStarFittingUvWithUrl:star.starUv starId:star.id];
                    }
                });
            }
        } else {
//            if (![GMLoginManager shareInstance].isVisitor) [self fetchStarListWithParameters:parameters completion:completion];
        }
    }];
}

+ (void)fetchStarFittingObjWithUrl:(NSString *)url starId:(NSString *)starId {
    [self fetchStarFittingObjWithUrl:url starId:starId completion:nil];
}

+ (void)fetchStarFittingObjWithUrl:(NSString *)url starId:(NSString *)starId completion:(ALFaceFittingDownloadStarCompletion)completion {
    NSString *filePath = [self getDataWithListKey:ALSTAR_FITTING_FINISH_OBJ_LIST key:starId];
    if (filePath) return;
    if (![url isNonEmpty]) {
        if (completion) completion(nil);
        return;
    }
    NSString *folderName = @"obj";
    NSString *documentPath = [[FileUtils getBasePath] stringByAppendingPathComponent:folderName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDirectory = YES;
    if (![fileManager fileExistsAtPath:documentPath isDirectory:&isDirectory]) {
        [fileManager createDirectoryAtPath:documentPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    [ALDownloadManager downloadTaskWithURL:url path:documentPath completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        NSString *fileName = [fileManager displayNameAtPath:filePath.absoluteString];
        if (!error && fileName) {
            NSString *path = [NSString stringWithFormat:@"%@/%@", folderName, fileName];
            [self saveDataWithObject:path listKey:ALSTAR_FITTING_FINISH_OBJ_LIST key:starId];
            if (completion) completion(path);
        } else if (completion) completion(nil);
    }];
}

+ (void)fetchStarFittingUvWithUrl:(NSString *)url starId:(NSString *)starId {
    [self fetchStarFittingUvWithUrl:url starId:starId completion:nil];
}

+ (void)fetchStarFittingUvWithUrl:(NSString *)url starId:(NSString *)starId completion:(ALFaceFittingDownloadStarCompletion)completion {
    NSString *filePath = [self getDataWithListKey:ALSTAR_FITTING_FINISH_UV_LIST key:starId];
    if (filePath) return;
    if (![url isNonEmpty]) {
        if (completion) completion(nil);
        return;
    }
    NSString *folderName = @"uv";
    NSString *documentPath = [[FileUtils getBasePath] stringByAppendingPathComponent:folderName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDirectory = YES;
    if (![fileManager fileExistsAtPath:documentPath isDirectory:&isDirectory]) {
        [fileManager createDirectoryAtPath:documentPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    [ALDownloadManager downloadTaskWithURL:url path:documentPath completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        NSString *fileName = [fileManager displayNameAtPath:filePath.absoluteString];
        if (!error && fileName) {
            NSString *path = [NSString stringWithFormat:@"%@/%@", folderName, fileName];
            [self saveDataWithObject:path listKey:ALSTAR_FITTING_FINISH_UV_LIST key:starId];
            if (completion) completion(path);
        } else if (completion) completion(nil);
    }];
}

+ (void)storeObjWithFilePath:(NSString *)filePath key:(NSString *)key completion:(void (^)(GMResponseOC * _Nonnull response))completion {
    [[ALUpLoadManager shareInstance] setFile:filePath getTokenType:GetTokenTypeSaoFace block:^(NSString *path) {
        NSMutableDictionary *parameters = [NSMutableDictionary new];
        [parameters setValue:ALScanManager.shareInstance.fittingId forKey:@"id"];
        [parameters setValue:path forKey:key];
        [self storeShareUploadWithParameters:parameters completion:completion];
    } failBlock:^(NSString *message) {
//        [self storeObjWithFilePath:filePath completion:completion];
    }];
}

+ (void)storeShareUploadWithParameters:(NSDictionary *)parameters completion:(void (^)(GMResponseOC * _Nonnull response))completion {
    [GMNetworking requestOCWithApi:API_FACE_SHARE_UPLOAD method:GMHTTPMethodPost parameters:parameters completion:^(GMResponseOC * _Nonnull response) {
        if (completion) completion(response);
    }];
}

+ (void)unlockStarNeedShareWithParameters:(NSDictionary *)parameters completion:(void (^)(GMResponseOC * _Nonnull))completion {
    [GMNetworking requestOCWithApi:API_FACE_SHARE_CODE method:GMHTTPMethodPost parameters:parameters completion:completion];
}

+ (void)unlockStarWithParameters:(NSDictionary *)parameters completion:(void (^)(GMResponseOC * _Nonnull))completion {
    [GMNetworking requestOCWithApi:API_FACE_CHOICE_STAR method:GMHTTPMethodPost parameters:parameters completion:completion];
}

+ (nullable NSString *)fetchStarFittingObjPathWithUrl:(NSString *)url starId:(NSString *)starId completion:(nullable ALFaceFittingDownloadStarCompletion)completion {
    NSString *path = [self getDataWithListKey:ALSTAR_FITTING_FINISH_OBJ_LIST key:starId];
    if (!path) [self fetchStarFittingObjWithUrl:url starId:starId completion:completion];
    return path;
}

+ (nullable NSString *)fetchStarFittingUvPathWithUrl:(NSString *)url starId:(NSString *)starId completion:(nullable ALFaceFittingDownloadStarCompletion)completion {
    NSString *path = [self getDataWithListKey:ALSTAR_FITTING_FINISH_UV_LIST key:starId];
    if (!path) [self fetchStarFittingUvWithUrl:url starId:starId completion:completion];
    return path;
}

+ (instancetype)getDataWithListKey:(NSString *)Listkey key:(NSString *)key {
    __block id object;
    dispatch_sync(url_finish_list_creation_queue(), ^{
        NSMutableDictionary *list = [[GMCache fetchObjectAtDocumentPathWithkey:Listkey] mutableCopy];
        object = list[key];
    });
    return object;
}

+ (void)saveDataWithObject:(id)object listKey:(NSString *)Listkey key:(NSString *)key {
    dispatch_async(url_finish_list_creation_queue(), ^{
        NSMutableDictionary *list = [[GMCache fetchObjectAtDocumentPathWithkey:Listkey] mutableCopy];
        if (!list) list = [NSMutableDictionary new];
        [list setValue:object forKey:key];
        [GMCache storeObjectAtDocumentPathWithkey:Listkey object:list];
    });
}

+ (void)removeDataWithListKey:(NSString *)Listkey key:(NSString *)key {
    dispatch_async(url_finish_list_creation_queue(), ^{
        NSMutableDictionary *list = [[GMCache fetchObjectAtDocumentPathWithkey:Listkey] mutableCopy];
        [list removeObjectForKey:key];
        [GMCache storeObjectAtDocumentPathWithkey:Listkey object:list];
    });
}
@end
