//
//  MMLocalDataBManager.m
//  Hello
//
//  Created by nana on 2020/9/15.
//  Copyright © 2020 nana. All rights reserved.
//

#import "MMLocalDataBManager.h"
#import <FMDB/FMDB.h>

@interface MMLocalDataBManager()

@property(nonatomic, strong)FMDatabaseQueue *dbQueue;
@property(nonatomic, strong)NSString *dbName;
@end

@implementation MMLocalDataBManager

+ (instancetype)sharedManager {
    static MMLocalDataBManager *sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager = [[MMLocalDataBManager alloc] init];
    });
    return sharedManager;
}
- (instancetype)init {
    if (self = [super init]) {
        [self setup];
        
    }
    return self;
}
- (void)setup {
    
    NSString *fileName = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) lastObject] stringByAppendingPathComponent:@"MMAutoUpdateDataTool.sqlite"];
     NSLog(@"dbPath = %@",fileName);
    //创建数据库
    self.dbQueue =  [FMDatabaseQueue databaseQueueWithPath:fileName];
//    self.dbQueue = [FMDatabaseQueue databaseQueueWithPath:@"/Users/nana/Desktop/wb.db"];
    [self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
        [db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_img (id integer PRIMARY KEY AUTOINCREMENT ,objectKey text,dataBlob blob, infoBlob blob)"];
    }];
}

/// 要上传的二进制 , 备注信息 ,该条记录的唯一标识符
- (BOOL)addWithID:(NSInteger)ID objectKey:(NSString *)objectKey updateData:(NSData *)updataData infoDict:(NSDictionary *)infoDict {
    if (!updataData || !objectKey) {
        return NO;
    }

    if (!infoDict) {
        infoDict = @{};
    }
    __block BOOL insertState = NO;
    NSData *infoDictData = [NSJSONSerialization dataWithJSONObject:infoDict options:NSJSONWritingPrettyPrinted error:nil];
    [self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
//        if (ID) {
           insertState = [db executeUpdateWithFormat:@"insert into t_img(id,objectKey, dataBlob,infoBlob) values(%ld,%@,%@,%@)",ID,objectKey,updataData,infoDictData];
//        }else {
//           insertState = [db executeUpdateWithFormat:@"insert into t_img(objectKey,dataBlob,infoBlob) values(%@,%@,%@)",objectKey,updataData,infoDictData];
//        }
//        NSLog(@"插入");
    }];
//    NSLog(@"返回");
    return insertState;
}

- (BOOL)addWithObjectKey:(NSString *)objectKey updateData:(NSData *)updataData infoDict:(NSDictionary *)infoDict {
    if (!updataData || !objectKey) {
          return NO;
      }
    
        if (!infoDict) {
            infoDict = @{};
        }
        __block BOOL insertState = NO;
        NSData *infoDictData = [NSJSONSerialization dataWithJSONObject:infoDict options:NSJSONWritingPrettyPrinted error:nil];
        [self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
            insertState = [db executeUpdateWithFormat:@"insert into t_img(objectKey, dataBlob,infoBlob) values(%@,%@,%@)",objectKey,updataData,infoDictData];
        }];
        return insertState;
    
}

- (BOOL)addWithObjectKey:(NSString *)objectKey updateData:(NSData *)updataData {
    
    if (!updataData || !objectKey) {
          return NO;
      }
      __block BOOL insertState = NO;
      [self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
          insertState = [db executeUpdateWithFormat:@"insert into t_img(objectKey,dataBlob) values(%@,%@)",objectKey,updataData];
//          NSLog(@"插入");
      }];
//      NSLog(@"返回");
      return insertState;
    
}
- (BOOL)deleteWithID:(NSInteger)ID {
    if (!ID) {
        return NO;
    }
    __block BOOL insertState = NO;
    [self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
           insertState = [db executeUpdateWithFormat:@"DELETE FROM t_img WHERE ID = %ld",ID];
//        NSLog(@"删除");
    }];
//    NSLog(@"返回");
    return insertState;
    
}
/// 查询
- (NSArray *)seleteWithID:(NSInteger)ID {
    NSMutableArray *reArray = [[NSMutableArray alloc] init];
    [self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
       FMResultSet *rs = [db executeQueryWithFormat:@"SELECT * FROM t_img WHERE ID = %ld",ID];
        [reArray addObjectsFromArray:[self arrayFromSet:rs]];
    }];
    
    return reArray;
}

/// 查询 大于ID的前几条数据
- (NSArray *)seleteWithGreaterThanOrEqualTo:(NSInteger)ID  limit:(NSInteger)limit {
    
    NSMutableArray *reArray = [[NSMutableArray alloc] init];
    [self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
       FMResultSet *rs = [db executeQueryWithFormat:@"SELECT * FROM t_img WHERE ID >= %ld LIMIT %ld",ID ,limit];
        [reArray addObjectsFromArray:[self arrayFromSet:rs]];
    }];
    
    return reArray;

}
/// 查询 包含objectKey 的前几条数据
- (NSArray *)selectWithLikeObjectKey:(NSString *)objectKey limit:(NSInteger)limit {
    NSMutableArray *reArray = [[NSMutableArray alloc] init];
    [self.dbQueue inDatabase:^(FMDatabase * _Nonnull db) {
       FMResultSet *rs = [db executeQueryWithFormat:@"SELECT * FROM t_img WHERE objectKey LIKE '%%%@%%' LIMIT %ld",objectKey ,limit];
        [reArray addObjectsFromArray:[self arrayFromSet:rs]];
    }];
    
    return reArray;
}

- (NSMutableArray *)arrayFromSet:(FMResultSet *)rs {
      
    NSMutableArray *reArray = [[NSMutableArray alloc] init];
    while (rs.next) {
        NSString *ID = [rs stringForColumn:@"ID"];
        NSString *objectKey = [rs stringForColumn:@"objectKey"];
        NSData *dataBlob = [rs dataForColumn:@"dataBlob"];
        NSData *infoBlobData = [rs dataForColumn:@"infoBlob"];
        NSDictionary *infoBlob = nil;
        if (infoBlobData) {
            infoBlob = [NSJSONSerialization JSONObjectWithData:infoBlobData options:NSJSONReadingFragmentsAllowed error:nil];
        }else {
            infoBlob = @{};
        }
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
            
        dict[@"ID"] = ID;
        dict[@"objectKey"] = objectKey;
        dict[@"updateData"] = dataBlob;
        dict[@"infoDict"] = infoBlob;
        [reArray addObject:dict];
    }
    return reArray;
    
}

@end
