//
//  CODownloadManager+ByURL.m
//  classonline
//
//  Created by hyz on 2019/3/20.
//  Copyright © 2019 offcn. All rights reserved.
//

#import "CODownloadManager+ByURL.h"
#import "CODownloadObject.h"
#import "WXCOMacros.h"
#import "WXCOUtility.h"

@implementation CODownloadManager (ByURL)

#pragma mark - Public Methods

- (void)co_startURLDownload:(NSString *)downloadURL
               withFileType:(COLessonType)fileType
                     userID:(NSString *)userID
        downloadRejectBlock:(nullable void (^)(NSMutableArray<CODownloadRejectModel *> * _Nullable))block
       withPriorityDownload:(BOOL)isPriority {
    if (WXCOIsNilOrNull(downloadURL) == YES || downloadURL.length <= 0) {
        if (WXCOIsNilOrNull(block) == NO) {
            CODownloadRejectModel *model = [[CODownloadRejectModel alloc] init];
            model.reason = DownloadRejectReasonEmptyURL;
            model.lesson_type = fileType;
            block([NSMutableArray arrayWithObjects:model, nil]); // 无网络环境下不能开始下载
        }
        return;
    }
    
    if ([self co_checkFileCanDownload:fileType] == NO) {
        if (WXCOIsNilOrNull(block) == NO) {
            CODownloadRejectModel *model = [[CODownloadRejectModel alloc] init];
            model.reason = DownloadRejectReasonUnsupported;
            model.lesson_type = fileType;
            block([NSMutableArray arrayWithObjects:model, nil]); // 无网络环境下不能开始下载
        }
        return;
    }
    
    downloadURL = [WXCOUtility urlWithString:downloadURL].absoluteString; // 编码处理
    NSMutableArray *downloadArray = [NSMutableArray arrayWithCapacity:1];
    self.newDownloadModels = nil;
    CODownloadObject *downloadObject = [self co_createDownloadObjectByURL:downloadURL withFileType:fileType];
    if (WXCOIsNilOrNull(downloadObject) == NO) {
        [downloadArray addObject:downloadObject];
    }
    
    [CODownloadModel batchAddDownloadModel2Database:self.newDownloadModels userID:userID];
    [self co_startDownload:downloadArray downloadRejectBlock:block subjoinRejectionArray:nil
      withPriorityDownload:isPriority];
}

- (void)co_pauseURLDownload:(NSString *)downloadURL {
    if (WXCOIsNilOrNull(downloadURL) || downloadURL.length <= 0) {
        [WXCOUtility showAlertWithMessage:@"抱歉，没有找到下载数据"];
        return;
    }
    
    downloadURL = [WXCOUtility urlWithString:downloadURL].absoluteString; // 编码处理
    CODownloadObject *object = [self co_getDownloadObjectByUrl:downloadURL];
    if (WXCOIsNilOrNull(object) == YES) {
        [WXCOUtility showAlertWithMessage:@"抱歉，没有找到下载数据"];
        return;
    }
    [self co_pauseDownload:[NSMutableArray arrayWithObjects:object, nil]];
}

- (void)co_deleteURLDownload:(NSString *)downloadURL
                      userID:(NSString *)userID
          withViewController:(UIViewController *)presentVC {
    if (WXCOIsNilOrNull(downloadURL) || downloadURL.length <= 0) {
        [WXCOUtility showAlertWithMessage:@"抱歉，没有找到下载数据"];
        return;
    }
    
    downloadURL = [WXCOUtility urlWithString:downloadURL].absoluteString; // 编码处理
    CODownloadObject *object = [self co_getDownloadObjectByUrl:downloadURL];
    if (WXCOIsNilOrNull(object) == YES) { // 没发现可以删除的对象
        [WXCOUtility showAlertWithMessage:@"抱歉，没有找到下载数据"];
        return;
    }
    
    if (presentVC == nil) {
        presentVC = [WXCOUtility getCurrentVC];
    }
    
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"确认删除此下载文件？"
                                                                     message:nil
                                                              preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelActoin = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * _Nonnull action) {}];
    __weak typeof(self) weakSelf = self;
    UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault
                                        handler:^(UIAlertAction * _Nonnull action) {
                                            [weakSelf co_deleteDownload:[NSMutableArray arrayWithObjects:object, nil] userID:userID];
                                        }];
    [alertVc addAction:cancelActoin];
    [alertVc addAction:deleteAction];
    [presentVC presentViewController:alertVc animated:YES completion:nil];
}

#pragma mark - Private Methods

/// 通过课件模型数据生成下载对象，如果已经存在则直接返回，否则新创建；PS:创建时特别注意如果该课件类型不满足下载条件，则会返回nil
/// 如果还有其他信息需要修改，请在返回的CODownloadObject对象中更新downloadModel中的值。然后执行updateModel2Database保存至数据库
/// @param downloadURL 下载地址
/// @param type 文件类型
/// @return 下载数据对象
- (CODownloadObject *)co_createDownloadObjectByURL:(NSString *)downloadURL withFileType:(COLessonType)type {
    CODownloadObject *object = [self co_getDownloadObjectByUrl:downloadURL];
    if (object == nil) { // 如果还未执行过下载
        if ([self co_checkFileCanDownload:type] == YES) { // 满足下载条件
            object = [[CODownloadObject alloc] initWithDownloadObject:
                      [self co_createDownloadModelByURL:downloadURL withFileType:type]];
            [self.allDownloads addObject:object];
            [self.downloadingQueue addObject:object];
        }
    }
    return object;
}


/// 通过URL和文件类型创建下载模型数据
/// @param downloadURL 课件信息
/// @param type 课件信息
/// @return 下载模型数据
- (CODownloadModel *)co_createDownloadModelByURL:(NSString *)downloadURL withFileType:(COLessonType)type {
    CODownloadModel *model = [[CODownloadModel alloc] init];
    model.course_id = rootCourseIdByOrdinaryDownload;
    model.course_name = @"其他下载";
    model.current_size = 0;
    model.down_date = [WXCOUtility getTimeNow];
    model.down_name = @"下载文件";
    model.down_state = stateNoDownload;
    model.down_url = downloadURL;
    model.lesson_id = [NSString stringWithFormat:@"%@_%.0f", lessonIdByOrdinaryDownloadPrefix, [WXCOUtility timestamp]];
    model.offline_code = @"";
    model.lesson_type = type;
    model.file_name = @"";
    model.total_size = 0; // 默认值，VOD下载只有下载进度，没有已下载文件的存储大小
    model.video_length = @"";
    model.need_sync = needSyncValueNO; // 不需要同步下载记录
    model.is_show = isShowValueNO;
    model.check_expired = checkExpiredValueNO;
    
    [self.newDownloadModels addObject:model]; // 新生成的下载模型数据
    return model;
}

/// 检测文件是否可以被下载
/// @param fileType 下载文件类型
/// @return 是否可以被下载
- (BOOL)co_checkFileCanDownload:(COLessonType)fileType {
    if (fileType == COLessonTypePdf || fileType == COLessonTypeVideo) {
        return YES;
    }
    return NO;
}

#pragma mark - Notification

#pragma mark - getter setter

@end
