//
//  XFDB.m
//  XFFruit
//
//  Created by freecui on 15/8/24.
//  Copyright (c) 2015年 Xummer. All rights reserved.
//

#import "XFDB.h"
#import "XFPhoto.h"

//FMDB
#define DATABASE_PATH [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]stringByAppendingString:@"/.db"]
@implementation XFDB

+ (instancetype)sharedInstance {
    static XFDB *_sharedinstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedinstance = [[self alloc]init];
    });
    
    return _sharedinstance;
}
+ (BOOL)checkTableCreatedInDb: (FMDatabase *)db {
    
    NSString *createStr = @"CREATE TABLE IF NOT EXISTS   'xfphoto'(ID  INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL  UNIQUE, photoData VARCHAR)";//,position INTEGER
    BOOL worked = [db executeUpdate:createStr];
    return worked;
}
- (BOOL)savePhoto: (XFPhoto *)aphoto {
    FMDatabase *db = [FMDatabase databaseWithPath:DATABASE_PATH];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return NO;
    }
    
    [XFDB checkTableCreatedInDb:db];
    
    NSString *insterStr = @"INSERT INTO 'xfphoto'('photoData') VALUES(?)";
    
    BOOL worked = [db executeUpdate:insterStr,aphoto.photoData];//[NSString stringWithFormat:@"%@",aphoto.photoData]
    
    [db close];
    
    return worked;
    
}

- (BOOL)deletePhoto: (NSData *)photoData {
    FMDatabase *db = [FMDatabase databaseWithPath:DATABASE_PATH];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return NO;
    }
    
    [XFDB checkTableCreatedInDb:db];
    
    NSString *delStr =[NSString stringWithFormat: @"DELETE  FROM xfphoto where photoData = %@",photoData];
    BOOL worked = [db executeUpdate:delStr];
    
    [db close];
    return worked;
}


- (NSMutableArray *)fetchAllPhotosFromLocal {
    NSMutableArray *resultArr = [NSMutableArray array];
    FMDatabase *db = [FMDatabase databaseWithPath:DATABASE_PATH];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return resultArr;
    }
    
    [XFDB checkTableCreatedInDb:db];
    FMResultSet *rs = [db executeQuery:@"select * from xfphoto"];
    while ([rs next]) {
        XFPhoto *xfPhoto = [[XFPhoto alloc]init];
        xfPhoto.photoData = [rs dataForColumn:@"photoData"];
       // xfPhoto.position = [rs intForColumn:@"position"];
        
        [resultArr addObject:xfPhoto];
    }
    
    [rs close];
    [db close];
    
    return resultArr;
}

- (NSMutableArray *)fetchAllPhotosDataFromLocal {
    NSMutableArray *resultArr = [NSMutableArray array];
    FMDatabase *db = [FMDatabase databaseWithPath:DATABASE_PATH];
    if (![db open]) {
        NSLog(@"数据库打开失败");
        return resultArr;
    }
    
    [XFDB checkTableCreatedInDb:db];
    FMResultSet *rs = [db executeQuery:@"select * from xfphoto"];
    while ([rs next]) {
        NSData *photoData = [rs dataForColumn:@"photoData"];
        [resultArr addObject:photoData];
    }
    
    [rs close];
    [db close];
    
    return resultArr;

}



@end
