//
//  DataManager.m
//  XFFruit
//
//  Created by 陈俊俊 on 15/8/12.
//  Copyright (c) 2015年 Xummer. All rights reserved.
//

#import "DataManager.h"
#import "FMDatabase.h"
@implementation DataManager
{
    FMDatabase *_database;
}
//非标准单例
+ (DataManager *)sharedDatabaseManager{
    static DataManager *manager = nil;
    @synchronized(self){
        if (manager == nil) {
            manager = [[self alloc] init];
        }
    }
    return manager;
}

- (void)createDB
{
    //先获取app.db在沙盒中的路径
    NSString *path = [self getFullDatabasePathFromFileName:@"XFFruit.db"];
    //创建数据库对象
    _database = [[FMDatabase alloc] initWithPath:path];
    //打开数据库
    if ([_database open]) {//第一次打开如果没有那么就创建并打开 如果有直接打开
        //打开成功 那么就创建表
        [self creatTable];
    }else{
        NSLog(@"open database:%@",[_database lastErrorMessage]);
    }
}

#pragma mark - 获取数据库文件的全路径
- (NSString *)getFullDatabasePathFromFileName:(NSString *)name{
    //获取沙盒路径
    NSString *path = NSHomeDirectory();
    NSString *docPath = [path stringByAppendingPathComponent:@"Documents"];
    //要判断Documents存在不存在
    NSFileManager *fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:docPath]) {//存在
        //返回文件在Documents 目录下得路径
        return [docPath stringByAppendingFormat:@"/%@",name];
    }else{
        NSLog(@"Documents不存在");
        //不存在可以自己创建一个Documents目录
        return nil;
    }
}
- (void)creatTable{
    NSArray *arr = @[@"CREATE TABLE IF NOT EXISTS kitchen(serial integer  PRIMARY KEY AUTOINCREMENT,foreign_id Varchar(1024),type Varchar(1024),title Varchar(1024),create_time Varchar(1024),name Varchar(1024),image Varchar(1024))",
                     @"CREATE TABLE IF NOT EXISTS menu(serial integer  PRIMARY KEY AUTOINCREMENT,id Varchar(1024),sUrl Varchar(1024),title Varchar(1024),works Varchar(1024),favourite Varchar(1024),view Varchar(1024),url Varchar(1024))",
                     @"CREATE TABLE IF NOT EXISTS fresh(serial integer  PRIMARY KEY AUTOINCREMENT,id Varchar(1024),title Varchar(1024),url Varchar(1024),time Varchar(1024),desp Varchar(1024))"];
    //遍历数组创建表
    for (NSString *sql in arr) {
        BOOL isSeccess = [_database executeUpdate:sql];
        if (!isSeccess) {
            NSLog(@"create table failed%@",[_database lastErrorMessage]);
        }
    }
}

@end
