#import "KLTRunLog.h"

@implementation KLTRunLog

- (NSArray *)listAllLog
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDir = [documentPaths objectAtIndex:0];
    
    NSString *path = [documentDir stringByAppendingPathComponent:@"runLog"];
    NSError *error = nil;
    
    NSArray *fileList = [fileManager contentsOfDirectoryAtPath:path error:&error];
    
    NSMutableArray *sortedPaths = [NSMutableArray new];
    for (NSString *p in fileList) {
        NSString *fullPath = [path stringByAppendingPathComponent:p];

        NSDictionary * attr = [NSFileManager.defaultManager attributesOfItemAtPath:fullPath error:nil];
        NSDate * modDate = [attr objectForKey:NSFileModificationDate];
     
        PathWithModDate * pathWithDate = [[PathWithModDate alloc] init];
        pathWithDate.path = p;
        pathWithDate.modDate = modDate;

        [sortedPaths addObject:pathWithDate];
    }
    // 对运行日志文件进行排序
    [sortedPaths sortUsingComparator:^ (PathWithModDate *path1, PathWithModDate *path2) {
        return [path2.modDate compare:path1.modDate];
    }];
    
    NSMutableArray *top10fileList = [[NSMutableArray alloc] init];
    
    for (int i = 0; i < sortedPaths.count; i++) {
        if (i >= 10) {
            break;
        }
        
        PathWithModDate *p = [sortedPaths objectAtIndex:i];
        [top10fileList addObject:p.path];
    }
    
    return top10fileList;
}

- (void)createNewCSV:(NSString *)sensorSN
{
    NSArray *array = [self listAllLog];
    NSInteger max = 0;
    
    for (id obj in array) {
        if (max < [obj componentsSeparatedByString:@"_"][0].intValue) {
            max = [obj componentsSeparatedByString:@"_"][0].intValue;
        }
    }

    NSString *newCSVPath = [NSString stringWithFormat:@"%ld_%@.csv", (long)(max + 1), sensorSN];
    
    [self setPath:newCSVPath];

    //NSLog(@"new csv path = %@", newCSVPath);
}

- (void)useCurrentCSV:(NSString *)sensorSN
{
    NSArray *array = [self listAllLog];
    NSInteger max = 0;
    
    for (id obj in array) {
        if ([obj containsString:sensorSN]) {
            if (max < [obj componentsSeparatedByString:@"_"][0].intValue) {
                max = [obj componentsSeparatedByString:@"_"][0].intValue;
            }
        }
    }

    if (max == 0) {
        max = 1;
    }
    
    NSString *currentCSVPath = [NSString stringWithFormat:@"%ld_%@.csv", (long)max, sensorSN];
    
    [self setPath:currentCSVPath];

    //NSLog(@"current csv path = %@", currentCSVPath);
}

- (void)setPath:(NSString *)path
{
    NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentDirectory = [documentDirectories objectAtIndex:0];

    _path = [[documentDirectory stringByAppendingPathComponent:@"runLog"] stringByAppendingPathComponent:path];
}

- (void) getPath
{
    //NSLog(@"Current runlog path = %@", self.path);
}

- (void)writeLog:(DEBUG_MODE)mode message:(NSString *)message
{
    if (_path == nil) {
        return;
    }
    
    NSOutputStream* output = [[NSOutputStream alloc] initToFileAtPath: _path append: YES];
    [output open];
    if (![output hasSpaceAvailable]) {
        //NSLog(@"No space available in %@", _path);
    } else {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_GB"]];
        [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"];
        NSDate *datenow = [NSDate date];
        NSString *currentTimeString = [formatter stringFromDate:datenow];

        //NSLog(@"currentTimeString =  %@",currentTimeString);
#if DEBUG
        NSString *debugLevel = @"debug";
#else
        NSString *debugLevel = @"release";
#endif
        
        NSString *debugMode;
        
        switch (mode) {
            case info:
                debugMode = @"INFO";
                break;
            case warn:
                debugMode = @"WARN";
                break;
            case error:
                debugMode = @"ERROR";
                break;
            default:
                debugMode = @"INFO";
                break;
        }
        
        NSString  *str = [[NSString alloc]initWithFormat:@"%@,%@,%@,%@\n", currentTimeString, debugMode, debugLevel, message];
        
    
        NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
        [output write:data.bytes maxLength:data.length];
    }
    [output close];
}

@end

@implementation PathWithModDate
@end
