//
//  DBOperation.m
//  zhuxun
//
//  Created by winsoft on 17/4/24.
//
//

#import "DBOperation.h"
#import <FMDB/FMDB.h>
#import "DBConfigureCenter.h"
#import <MJExtension/MJExtension.h>
//static FMDatabaseQueue *dbqueue;
@interface DBOperation()
@property (nonatomic , strong) FMDatabaseQueue *dbqueue;

@end

@implementation DBOperation
+ (instancetype)dbOperationWithPath:(NSString *)path
{
    DBOperation *dbOperation = [[DBOperation alloc]init];
    
    if (!dbOperation.dbqueue) {
        dbOperation.dbqueue = [FMDatabaseQueue databaseQueueWithPath:path];
    }
    
    return dbOperation;
    
}

- (void)creatDBbySQL:(NSString *)sql Path:(NSString *)path
{

    [self.dbqueue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:sql];
        
    }];
    


    //dbqueue = [FMDatabaseQueue databaseQueueWithPath:path];
//    if (dbqueue == nil) {
//        dbqueue = [FMDatabaseQueue databaseQueueWithPath:path];
//    }
//    
//    [dbqueue inDatabase:^(FMDatabase *db) {
//        [db executeUpdate:sql];
//        
//    }];
    
}

- (void)creatDBWithTableName:(NSString *)tableName dbModelClass:(Class)dbModelClass Path:(NSString *)path autoUpgrade:(BOOL)autoUpgrade
{
    NSString *sql = [DBConfigureCenter getDBTableWithTableName:tableName className:dbModelClass];
    
    [self creatDBbySQL:sql Path:path];
    
    //自动升级.
    if (autoUpgrade) {
        
          [self judgeCloumExistAndAutoUpdateWithTableName:tableName allCloumnName_TypeArray:[DBConfigureCenter sqlCloumnCheckWithClassName:dbModelClass]];
    }
}

//自动升级.
- (void)judgeCloumExistAndAutoUpdateWithTableName:(NSString *)tableName allCloumnName_TypeArray:(NSArray<DBStructModel *> *)allCloumnName_TypeArray
{
    
    NSString *sql = [NSString stringWithFormat:@"pragma table_info (%@)",tableName];
    
    __weak typeof(self)weakself = self;
    
    [self quaryDBbySQL:sql result:^(NSMutableArray *array) {
        
        NSArray *dbStructArray = [DBStructModel mj_objectArrayWithKeyValuesArray:array];
        
        
        for (DBStructModel *dbModel in allCloumnName_TypeArray) {
            
            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@",dbModel.name];
            
            //如果name在数据库返回的字段内找不到,则插入.
            NSArray *targetKeyArray = [dbStructArray filteredArrayUsingPredicate:predicate];
            
            if (!targetKeyArray.count) {
                
                NSString *alertStr = [NSString stringWithFormat:@"ALTER TABLE %@ ADD %@ %@",tableName,dbModel.name,dbModel.type];
                
                [weakself addDataToDBWithSQL:alertStr];
                
            }
        }
        
    }];
}


//查询目标群组
- (void)quaryDBbySQL:(NSString *)sql result:(void(^)(NSMutableArray *array))result
{
    __block FMResultSet *rs = nil;
    NSMutableArray *tempArray = [NSMutableArray array];
    [self.dbqueue inDatabase:^(FMDatabase *db) {
        
        
        rs = [db executeQuery:sql];
        
        while (rs.next) {
            //获取nsdata
//            NSData *data = rs.resultDictionary ;//[rs dataForColumn:nil];
//            //将nsdata转成weibostatusmodel
//            GroupObject *groupObject = [NSKeyedUnarchiver unarchiveObjectWithData:data];
//            [tempArray addObject:groupObject];
            NSDictionary *dict = rs.resultDictionary;
            [tempArray addObject:dict];
            
        }
    }];
    
    if (tempArray.count) {
        result(tempArray);
    }else result (nil);
    
}

//插入模型
- (void)addDataToDBbySQL:(NSString *)sql statuDBmodel:(id )model
{
    //遍历model...
//    [dbqueue inDatabase:^(FMDatabase *db) {
//        [db executeUpdate:sql, dbmodel.access_token,dbmodel.idstr
//         ,dbmodel.data];
//    }];
}

- (void)addDataToDBWithSQL:(NSString *)sql
{
    [self.dbqueue inDatabase:^(FMDatabase *db) {
        [db executeUpdate:sql];
    }];
}
@end
