//
//  CODownloadModel.m
//  classonline
//
//  Created by hyz on 2019/2/25.
//  Copyright © 2019 offcn. All rights reserved.
//

#import "CODownloadModel.h"
//#import "CODataBase+Download.h"
//#import "VodPlaybackManager.h"
//#import "COPlaybackDownloadManager.h"
#import "CODownloadObject.h"
#import <YYKit/YYKit.h>


/// 下载标识，key是用户ID
static NSString * const downloadIdentifyCacheName = @"downloadIdentify";
/// 下载模型存储名称，key是下载的URL
static NSString * const downloadModelCacheName = @"downloadModel";

@implementation CODownloadModel

#pragma mark - NSCoding & NSCopying

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [self modelEncodeWithCoder:aCoder];
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    return [self modelInitWithCoder:aDecoder];
}

- (id)copyWithZone:(NSZone *)zone {
    return [self modelCopy];
}

- (NSUInteger)hash {
    return [self modelHash];
}

- (BOOL)isEqual:(id)object {
    return [self modelIsEqual:object];
}

#pragma mark - Init

- (instancetype)init {
    if (self = [super init]) {
        _down_state = -1;
        _pdf_type = COPdfTypeHandouts;
        _need_sync = needSyncValueNO;
        _is_show = isShowValueNO;
        _check_expired = checkExpiredValueNO;
    }
    return self;
}

#pragma mark - Public Methods

+ (NSMutableArray <CODownloadModel *> *)getUserAllDownloadDataWithUserID:(NSString *)userID {
//    WXPersonInfoModel *infoModel = [[WXPersonInfo shared] personInfo];
    YYCache *cache = [YYCache cacheWithName:downloadIdentifyCacheName];
    NSMutableArray *arrM = [((NSArray *)[cache objectForKey:userID]) mutableCopy];
    NSMutableArray *modelArrM = [NSMutableArray array];
    if (arrM != nil) {
        for (NSString *url in arrM) {
            YYCache *downloadCache = [YYCache cacheWithName:downloadModelCacheName];
            CODownloadModel *model = (CODownloadModel *)[downloadCache objectForKey:url];
            if (model != nil) {
                [modelArrM addObject:model];
            }
        }
    }
    
    return modelArrM;
}

+ (void)batchUpdateDownloadState2Database:(NSMutableArray <CODownloadModel *> *)modelArray {
//    [[CODataBase sharedInstance] batchUpdateDownloadState:modelArray];
}

+ (void)batchAddDownloadModel2Database:(NSMutableArray <CODownloadModel *> *)modelArray userID:(NSString *)userID {
    if (modelArray == nil || modelArray.count <= 0) {
        return;
    }
    for (CODownloadModel *mdoel in modelArray) {
        [mdoel addModel2DatabaseWithUserID:userID];
    }
}

- (NSString *)getLocalDownloadFullPath {
    if (WXCOIsNilOrNull(self.file_name) == YES || self.file_name.length <= 0) {
        return @"";
    }
    
    return [NSString stringWithFormat:@"%@/%@", [self getLocalDownloadCachePath], self.file_name];
}

- (NSString *)getLocalDownloadCachePath {
    NSString *cacheDir = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
                           objectAtIndex:0] stringByAppendingString:@"/LessonFile"];
    
    if (NO == [[NSFileManager defaultManager] fileExistsAtPath:cacheDir]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:cacheDir withIntermediateDirectories:YES
                                                   attributes:nil error:nil];
        NSError *error = nil;
        NSURL *URL= [NSURL fileURLWithPath:cacheDir];
        BOOL success = [URL setResourceValue:[NSNumber numberWithBool:YES]
                                      forKey:NSURLIsExcludedFromBackupKey error:&error];
        if(NO == success) {
            NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
        }
    }
    return cacheDir;
}

- (BOOL)checkDownloadComplete {
    if ([self checkInsideDownloaderCanDownloadLessonType] == YES) {
        if (self.down_state == stateCompleted &&
            [[NSFileManager defaultManager] fileExistsAtPath:[self getLocalDownloadFullPath]]) {
            return YES;
        }
    }

    if (self.lesson_type == COLessonTypePlayback) {
        if (self.live_type == COLiveTypeOffcnLive) {
            return [CODownloadObject checkOffcnLiveCompleteDownload:self.down_url];
        } else if (self.live_type == COLiveTypeGenseeLive) {
//            return [[VodPlaybackManager sharedManager] checkVodCompleteDownload:self.down_url];
        }
    }
    
    return NO;
}

- (NSString *)lessonVideoLengthDesc {
    if (self.lesson_type != COLessonTypeVideo) {
        return @"";
    }
    return [NSString stringWithFormat:@"时长：%@", self.video_length];
}

- (NSString *)lessonWatchProgressDesc {
    if (WXCOIsNilOrNull(self.lesson_id) == YES || self.lesson_id.length <= 0) {
        return @"未观看";
    }
    
    // 关联学习记录数据，计算观看进度
    return @"未观看";
}

- (BOOL)checkPlaybackLessonType {
    if (self.lesson_type == COLessonTypePlayback) {
        if (self.live_type == COLiveTypeOffcnLive || self.live_type == COLiveTypeGenseeLive) {
            return YES;
        }
    }
    return NO;
}

- (BOOL)checkInsideDownloaderCanDownloadLessonType {
    if (self.lesson_type == COLessonTypeVideo ||
        self.lesson_type == COLessonTypePdf) {
        return YES;
    }
    return NO;
}

- (void)addModel2DatabaseWithUserID:(NSString *)userID {
//    WXPersonInfoModel *infoModel = [[WXPersonInfo shared] personInfo];
    YYCache *cache = [YYCache cacheWithName:downloadIdentifyCacheName];
    __weak typeof(self) weakSelf = self;
    NSMutableArray *arrM = [((NSArray *)[cache objectForKey:userID]) mutableCopy];
    if (arrM == nil) {
        arrM = [NSMutableArray array];
    }
    if ([arrM containsObject:weakSelf.down_url] == NO) {
        [arrM addObject:weakSelf.down_url];
    }
    [cache setObject:arrM forKey:userID];
    
    YYCache *downloadCache = [YYCache cacheWithName:downloadModelCacheName];
    [downloadCache setObject:self forKey:self.down_url];
}

- (void)deleteModelFromDatabaseWithUserID:(NSString *)userID {
//    WXPersonInfoModel *infoModel = [[WXPersonInfo shared] personInfo];
    YYCache *cache = [YYCache cacheWithName:downloadIdentifyCacheName];
    __weak typeof(self) weakSelf = self;
    
    
    NSMutableArray *arrM = [((NSArray *)[cache objectForKey:userID]) mutableCopy];
    if (arrM == nil) {
        arrM = [NSMutableArray array];
    }
    if ([arrM containsObject:weakSelf.down_url] == NO) {
        [arrM removeObject:weakSelf.down_url];
    }
    [cache setObject:arrM forKey:userID];
    
    YYCache *downloadCache = [YYCache cacheWithName:downloadModelCacheName];
    [downloadCache removeObjectForKey:self.down_url];
}

- (void)updateModel2Database {
    YYCache *cache = [YYCache cacheWithName:downloadModelCacheName];
    [cache setObject:self forKey:self.down_url];
}

#pragma mark - Private Methods

#pragma mark - getter setter

@end

@implementation CODownloadRejectModel

- (instancetype)init {
    if (self = [super init]) {
        _lesson_id = @"";
        _lesson_type = NSNotFound;
    }
    return self;
}

- (NSString *)description {
    if (WXCOIsNilOrNull(self.lesson_name) || self.lesson_name.length <= 0) {
        return [self downloadReasonDescStr];
    }
    return [NSString stringWithFormat:@"【%@】不能下载，原因：%@", self.lesson_name, [self downloadReasonDescStr]];
}

- (NSString *)downloadReasonDescStr {
    NSString *reasonDesc = @"原因未知";
    switch (self.reason) {
        case DownloadRejectReasonEmptyData:
            reasonDesc = @"数据源为空";
            break;
        case DownloadRejectReasonEmptyURL:
            reasonDesc = @"下载地址为空";
            break;
        case DownloadRejectReasonUnsupported:
            reasonDesc = @"下载类型不支持";
            break;
        case DownloadRejectReasonOfflineCode:
            reasonDesc = @"直播回放房间号为空";
            break;
        case DownloadRejectReasonPassword:
            reasonDesc = @"直播回放口令码为空";
            break;
        case DownloadRejectReasonNoPlayback:
            reasonDesc = @"没有回放数据";
            break;
        case DownloadRejectReasonEmptyList:
            reasonDesc = @"本次操作未发现可执行下载的文件";
            break;
        case DownloadRejectReasonNoNetwork:
            reasonDesc = @"网络不给力，请检查你的网络设置";
            break;
        case DownloadRejectReasonWWANNetwork:
            reasonDesc = @"用户不允许消耗流量";
            break;
        default:
            break;
    }
    return reasonDesc;
}

@end

@implementation CODownloadPaperModel

@end
