package com.imofan.android.basic;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * 魔方数据处理服务类
 */
public class MFDatabaseManager extends SQLiteOpenHelper {
    private final static String LOG_TAG = Mofang.LOG_TAG + "_MFDatabaseHelper";
    private final static String DATABASE = "mofang_data_analysis.db";   //数据库名称
    private final static int VERSION = 10;                                   //数据库版本号

    //数据库初始化语句
    private final static String INIT_SQL = MFStatEvent.CREATE_SQL + MFOpenEvent.CREATE_SQL 
    		+ MFNetworkInfo.CREATE_SQL+MFAPPBasicInfo.CREATE_SQL;
    private final static String UPGRADE_SQL = MFOpenEvent.UPGRADE_SQL;

    private static MFDatabaseManager self = null;

    //隐藏构造函数，以实现单例模式
    private MFDatabaseManager(Context context) {
        super(context, DATABASE, null, VERSION);
    }

    //获取该类的单例对象
    public static synchronized MFDatabaseManager getInstance(Context context) {
        if(self == null && context != null) {
            self = new MFDatabaseManager(context);
        }
        return self;
    }

    //初始化数据库
    @Override
    public void onCreate(SQLiteDatabase database) {
        String[] initSqls = INIT_SQL.split(";");
        for(String initSql : initSqls) {
            if(initSql != null && initSql.trim().length() > 1) {
                if(Mofang.DEBUG) {
                    Log.d(LOG_TAG, "[onCreate]Execute SQL: " + initSql + ";");
                }
                database.execSQL(initSql + ";");
            }
        }
        if(null!=UPGRADE_SQL && !"".equals(UPGRADE_SQL)){
    		String[] upgradeSqls = UPGRADE_SQL.split(";");
    		for(String upgradeSql : upgradeSqls) {
    			if(Mofang.DEBUG) {
    				Log.d(LOG_TAG, "[onUpgrade]Execute SQL: " + upgradeSql + ";");
    			}
    			try{
        			database.execSQL(upgradeSql + ";");
    			}catch(SQLiteException e){
    				e.printStackTrace();
    			}

    		}
    	}
        
    }

    //更新数据库
    @Override
    public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
        onCreate(database);
        
        database.execSQL(MFNetworkInfo.DELETE_SQL);	
        database.execSQL(MFAPPBasicInfo.DELETE_SQL);
    }
}
