package com.mjsheng.myappstore.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.List;

public class DBHelper {
    private static final String DATABASE_NAME = "xueshibao.db";
    private static final int DATABASE_VERSION = 1;

    @SuppressWarnings("unused")
    private final Context mContext;
    private DatabaseHelper mDatabaseHelper;

    private SQLiteDatabase db;

    public DBHelper(Context context) {
        this.mContext = context;
        mDatabaseHelper = new DatabaseHelper(context);
    }

    public DatabaseHelper returnDb(Context context){
        close();
        if (mDatabaseHelper == null) {
            mDatabaseHelper = new DatabaseHelper(context);
        }
        return mDatabaseHelper;
    }
    public DBHelper open() throws SQLException {
        close();
        db = mDatabaseHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDatabaseHelper.close();
    }

    public boolean deleteRow(String tableName, long rowId) {
        open();
        return db.delete(tableName, "_id =" + rowId, null) > 0;
    }

    public void deleteRow(String tableName, List<String> list) {
        open();
        db.beginTransaction(); // 手动设置开始事务
        for (String v : list) {
            db.delete(tableName,  v, null);
        }
        db.setTransactionSuccessful(); // 设置事务处理成功，不设置会自动回滚不提交
        db.endTransaction(); // 处理完成
        db.close();
    }

    public boolean deleteRow(String tableName, String whereSql) {
        open();
        return db.delete(tableName, whereSql, null) > 0;
    }

    public void deleteTable(String tableName) {
        open();
        db.execSQL("DROP TABLE IF EXISTS " + tableName);
        if (tableName.equals(DBSqlBuilder.APPLICATION_HISTORY)) {
            db.execSQL(DBSqlBuilder.BuilderHistoryTable());
        } else if (tableName.equals(DBSqlBuilder.APPLICATION_MESSAGE)) {
            db.execSQL(DBSqlBuilder.BuilderMessageTable());
        } else if (tableName.equals(DBSqlBuilder.CONFIG_APP_TABLE)) {
            db.execSQL(DBSqlBuilder.BuilderConfigTable());
        } else if (tableName.equals(DBSqlBuilder.COURSE_TABLE)) {
            db.execSQL(DBSqlBuilder.BuilderCourseTable());
        }else if (tableName.equals(DBSqlBuilder.DETAIL_LOG_TABLE)) {
            db.execSQL(DBSqlBuilder.BuilderDetailLogTable());
        }  else if (tableName.equals(DBSqlBuilder.DOWNLOADING_TABLE)) {
            db.execSQL(DBSqlBuilder.BuilderDownloadTable());
        }
    }

    public Cursor getCursor(String tableName, String whereStr) {
        open();
        return db.rawQuery("select * from " + tableName + " " + whereStr, null);
    }

    public Cursor getCursorBySql(String sqlStr) {
        open();
        return db.rawQuery(sqlStr, null);
    }


    public Cursor getCursorGroupBy(String tableName, String columnName,
                                   String groupBy) throws SQLException {
        open();
        return db.rawQuery("select " + columnName + " from " + tableName + " "
                + groupBy, null);
    }

    public Cursor getCursor(String tableName, String columeName, int value)
            throws SQLException {
        open();
        return db.rawQuery("select * from " + tableName + " where "
                + columeName + "='" + value + "'", null);
    }

    public Cursor getTopN(String tableName, String columeName, int topN)
            throws SQLException {
        open();
        return db.rawQuery("select * from " + tableName + " order by "
                + columeName + " desc limit " + topN, null);
    }

    // 批量处理
    public void insertListValues(String tableName, List<ContentValues> list) {
        open();
        db.beginTransaction();
        for (ContentValues v : list) {
            db.insert(tableName, null, v);
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        db.close();
    }

    public boolean insertValues(String tableName, ContentValues values) {
        open();
        return db.insert(tableName, null, values) > 0;
    }

    public boolean updateValues(String tableName, ContentValues values,
                                String whereStr) {
        open();
        return db.update(tableName, values, whereStr, null) > 0;
    }

    public boolean updateValues(String tableName, ContentValues values,
                                String whereStr, String[] whereArgs) {
        open();
        return db.update(tableName, values, whereStr, whereArgs) > 0;
    }

    public void InsertValuesWithTrans(String tableName, ContentValues values) {
        open();
        db.beginTransaction();
        db.insert(tableName, null, values);
        db.endTransaction();
    }

    public boolean updateColumeValue(String tableName, String columeName,
                                     int value, String whereColume, String whereValue) {
        ContentValues args = new ContentValues();
        args.put(columeName, value);
        open();
        return db.update(tableName, args,
                whereColume + "='" + whereValue + "'", null) > 0;
    }

    public static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(DBSqlBuilder.BuilderHistoryTable());
            db.execSQL(DBSqlBuilder.BuilderMessageTable());
            db.execSQL(DBSqlBuilder.BuilderConfigTable());
            db.execSQL(DBSqlBuilder.BuilderCourseTable());
            db.execSQL(DBSqlBuilder.BuilderDetailLogTable());
            db.execSQL(DBSqlBuilder.BuilderDownloadTable());
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + DBSqlBuilder.APPLICATION_HISTORY);
            db.execSQL("DROP TABLE IF EXISTS " + DBSqlBuilder.APPLICATION_MESSAGE);
            db.execSQL("DROP TABLE IF EXISTS " + DBSqlBuilder.CONFIG_APP_TABLE);
            db.execSQL("DROP TABLE IF EXISTS " + DBSqlBuilder.COURSE_TABLE);
            db.execSQL("DROP TABLE IF EXISTS " + DBSqlBuilder.DETAIL_LOG_TABLE);
            db.execSQL("DROP TABLE IF EXISTS " + DBSqlBuilder.DOWNLOADING_TABLE);
            onCreate(db);
        }
    }
}