package com.rv.im.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.rv.im.ImSetting;
import com.rv.im.db.table.ChatConversation;
import com.rv.im.db.table.ChatMessage;
import com.rv.im.db.table.Customer;
import com.rv.im.db.table.DownBean;
import com.rv.im.log.LogUtil;

import java.sql.SQLException;


public class SQLiteHelper extends OrmLiteSqliteOpenHelper {

    public static final String DATABASE_NAME = "rv_im.db";
    private static final int DATABASE_VERSION = 1;

    private static SQLiteHelper instance = null;

    private SQLiteHelper(Context context) {
        super(context, ImSetting.getUserId() + DATABASE_NAME, null, DATABASE_VERSION);
        LogUtil.d("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "用户id" + ImSetting.getUserId());
    }

    public static SQLiteHelper getInstance(Context context) {
        if (instance == null) {
            instance = new SQLiteHelper(context);
        }
        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase db, ConnectionSource connSource) {
        createTables(connSource);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, ConnectionSource connSource, int oldVersion, int newVersion) {
    }

    private void createTables(ConnectionSource connSource) {
        try {
            TableUtils.createTableIfNotExists(connSource, ChatMessage.class);
            TableUtils.createTableIfNotExists(connSource, Customer.class);
            TableUtils.createTableIfNotExists(connSource, DownBean.class);
            TableUtils.createTableIfNotExists(connSource, ChatConversation.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public static void closeDb() {
        if (instance != null) {
            try {
                instance.getConnectionSource().close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                instance = null;
            }
        }
    }

}
