//
//  DatabaseMgr.m
//  Macalline
//
//  Created by JianjiYuan on 14-12-4.
//  Copyright (c) 2014年 JianjiYuan. All rights reserved.
//

#import "DBInstance.h"

#define DEFAULT_DB_NAME @"Macalline.db"

@implementation DBInstance

+ (instancetype)getInstance
{
    static DBInstance *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[DBInstance alloc] init];
    });
    return instance;
}

- (instancetype)init
{
    if (self = [super init]) {
        BOOL success = YES;
        BOOL isDataBaseExist = NO;
        NSError *error;
        NSFileManager *fm = [NSFileManager defaultManager];
        NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:DEFAULT_DB_NAME];
        
        isDataBaseExist = [fm fileExistsAtPath:writableDBPath];
        if (!isDataBaseExist) {
            NSString *defaultDBPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:DEFAULT_DB_NAME];
            if (success) {
                success = [fm copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
                if (!success) {
                    DLog(@"%@",[error description]);
                }else{
                    _db = [FMDatabase databaseWithPath:writableDBPath];
                    [_db setLogsErrors:true];
                    [_db setTraceExecution:true];
                    [_db setShouldCacheStatements:YES];
                }
            }
            
        }else{
            _db = [FMDatabase databaseWithPath:writableDBPath];
            [_db setLogsErrors:true];
            [_db setTraceExecution:true];
            [_db setShouldCacheStatements:YES];
        }
        _dbQueue = [FMDatabaseQueue databaseQueueWithPath:writableDBPath];

    }
    return self;
}

- (FMDatabaseQueue *)queue
{
    return _dbQueue;
}

- (FMDatabase *)db
{
    return _db;
}

#pragma mark 删除数据库
// 删除数据库
- (void)deleteDatabse
{
    BOOL success;
    NSError *error;
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    // delete the old db.
    if ([fileManager fileExistsAtPath:DEFAULT_DB_NAME])
    {
        [_db close];
        success = [fileManager removeItemAtPath:DEFAULT_DB_NAME error:&error];
        if (!success) {
            NSAssert1(0, @"Failed to delete old database file with message '%@'.", [error localizedDescription]);
        }
    }
}

// 判断是否存在表
- (BOOL)isTableOK:(NSString *)tableName
{
    FMResultSet *rs = [_db executeQuery:@"SELECT count(*) as 'count' FROM sqlite_master WHERE type ='table' and name = ?", tableName];
    while ([rs next])
    {
        // just print out what we've got in a number of formats.
        int count = [rs intForColumn:@"count"];
        DLog(@"isTableOK %d", count);
        
        if (0 == count)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    
    return NO;
}

// 获得表的数据条数
- (BOOL)getTableItemCount:(NSString *)tableName
{
    NSString *sqlstr = [NSString stringWithFormat:@"SELECT count(*) as 'count' FROM %@", tableName];
    FMResultSet *rs = [_db executeQuery:sqlstr];
    while ([rs next])
    {
        // just print out what we've got in a number of formats.
        int count = [rs intForColumn:@"count"];
        DLog(@"TableItemCount %d", count);
        
        return count;
    }
    
    return 0;
}

// 创建表
- (BOOL)createTable:(NSString *)tableName withArguments:(NSString *)arguments
{
    NSString *sqlstr = [NSString stringWithFormat:@"CREATE TABLE %@ (%@)", tableName, arguments];
    if (![_db executeUpdate:sqlstr])
        //if ([DB executeUpdate:@"create table user (name text, pass text)"] == nil)
    {
        DLog(@"Create db error!");
        return NO;
    }
    
    return YES;
}

// 删除表
- (BOOL) deleteTable:(NSString *)tableName
{
    NSString *sqlstr = [NSString stringWithFormat:@"DROP TABLE %@", tableName];
    if (![_db executeUpdate:sqlstr])
    {
        DLog(@"Delete table error!");
        return NO;
    }
    
    return YES;
}

// 清除表
- (BOOL) eraseTable:(NSString *)tableName
{
    NSString *sqlstr = [NSString stringWithFormat:@"DELETE FROM %@", tableName];
    if (![_db executeUpdate:sqlstr])
    {
        DLog(@"Erase table error!");
        return NO;
    }
    
    return YES;
}

@end
