//
//  KMCloudDownloadOperationQueue.m
//  Cisdem PDFMaster
//
//  Created by 万军 on 2020/2/25.
//  Copyright © 2020 WanJun. All rights reserved.
//

#import "KMCloudDownloadOperationQueue.h"
#import "KMCloudOperation.h"
//#import "KMSyncHistoricalFileManager.h"

@interface KMCloudDownloadOperationQueue ()

@end

@implementation KMCloudDownloadOperationQueue

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

+ (instancetype)sharedInstance {
    static KMCloudDownloadOperationQueue *sharedInstance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [KMCloudDownloadOperationQueue new];
        sharedInstance.downloadingOperations = [NSMutableDictionary dictionary];
    });
    return sharedInstance;
}

- (void)downloadAlert:(NSString *)alertString filePath:(NSString *)filePath {
    NSAlert *alert = [NSAlert alertWithMessageText:alertString
                                     defaultButton:NSLocalizedString(@"OK", nil)
                                   alternateButton:nil
                                       otherButton:nil
                         informativeTextWithFormat:@"%@ %@", alertString, filePath];
    [alert runModal];
}

#pragma mark - download

- (void)addDownloadOperation:(NSOperation *)op
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(serverCloudFileManagerDownloadSuccessfulNotification:) name:KMServerCloudFileManagerDownloadSuccessfulNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(serverCloudFileManagerDownloadFailureNotification:) name:KMServerCloudFileManagerDownloadFailureNotification object:nil];
    
    if ([op isKindOfClass:[KMCloudOperation class]]) {
        KMCloudOperation *operation = (KMCloudOperation *)op;
        if (operation.serverType == KMDropbox) {
            [self addDropboxDownloadOperation:(KMCloudOperation *)op];
        } else if (operation.serverType == KMGoogleDrive) {
            [self addGoogleDriveDownloadOperation:(KMCloudOperation *)op];
        }
//        KMSyncHistoricalFile *historicalFile = [[[KMSyncHistoricalFile alloc] initWithOperationQueue:operation] autorelease];
//        [[KMSyncHistoricalFileManager defaultManager] addHistoricalFile:historicalFile];
    }
}

- (void)addDropboxDownloadOperation:(KMCloudOperation *)op {
    if ([self isDownloadOperationExisting:op.filePath]) {
        NSLog(@"KMDropboxOperation exists %@", op);
        return;
    }
    
    if (![self.downloadingOperations objectForKey:op.filePath]) {
        @synchronized (self) {
            [self.downloadingOperations setObject:op forKey:op.filePath];
        }
        
        [self addOperation:op];
    }
}

- (void)addGoogleDriveDownloadOperation:(KMCloudOperation *)op {
    if ([self isDownloadOperationExisting:op.filePath]) {
        NSLog(@"KMGoogleDriveOperation exists %@", op);
        return;
    }
    
    if (![self.downloadingOperations objectForKey:op.filePath]) {
        @synchronized (self) {
            [self.downloadingOperations setObject:op forKey:op.filePath];
        }
        
        [self addOperation:op];
    }
}

- (NSOperation *)isDownloadOperationExisting:(NSString *)urlString {
    for (NSString *url in self.downloadingOperations.allKeys) {
        if ([url isEqualToString:urlString]) {
            return [self.downloadingOperations objectForKey:url];
        }
    }
    return nil;
}

#pragma mark - cancel

- (void)cancel:(NSString *)urlString {
    KMCloudOperation *op = [self.downloadingOperations objectForKey:urlString];
    if (op) {
        @synchronized (self) {
            [self.downloadingOperations removeObjectForKey:urlString];
        }
    }
}

- (void)cancelAll {
    @synchronized (self) {
        [self.downloadingOperations removeAllObjects];
    }
    [self cancelAllOperations];
}

#pragma mark - NSNotificationCenter

- (void)serverCloudFileManagerDownloadSuccessfulNotification:(NSNotification *)notification {
    if (notification.object) {
        KMCloudOperation *operation = (KMCloudOperation *)notification.object;
        if ([self.downloadingOperations objectForKey:operation.filePath]) {
            @synchronized (self) {
                [self.downloadingOperations removeObjectForKey:operation.filePath];
            }
        }
    }
}

- (void)serverCloudFileManagerDownloadFailureNotification:(NSNotification *)notification {
    if (notification.object) {
        KMCloudOperation *operation = (KMCloudOperation *)notification.object;
        if ([self.downloadingOperations objectForKey:operation.filePath]) {
            @synchronized (self) {
                [self downloadAlert:NSLocalizedString(@"Download Failed", nil) filePath:[operation.toPath lastPathComponent]];
                [self.downloadingOperations removeObjectForKey:operation.filePath];
            }
        }
    }
}
@end