package com.example.map.database;

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

import com.example.map.enity.User;

import java.util.ArrayList;

public class UserDBHelper extends SQLiteOpenHelper {

    private  static final String DB_NAME="user.db";
    private  static final String TABLE_NAME="user_table";
    private  static final  int DB_VERSION=1;
    private  static UserDBHelper mHelper = null;
    private  SQLiteDatabase mRDB=null;//用来读
    private  SQLiteDatabase mWDB=null;//用来写
    public SQLiteDatabase db;

    //参数为上下文context，所谓上下文就是这个类所在包的路径
    public UserDBHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        db = getReadableDatabase();
    }

    //利用单例模式获取数据库帮助器的唯一实例
    public static UserDBHelper getInstance(Context context){
        if(mHelper==null){
            mHelper=new UserDBHelper(context);
        }
        return  mHelper;
    }

    //打开数据库的读连接
    public SQLiteDatabase openReadLink(){
        if (mRDB==null || !mRDB.isOpen()){
            mRDB= mHelper.getReadableDatabase();
        }
        return mRDB;
    }
    //打开数据库的写连接
    public SQLiteDatabase openWriteLink(){
        if (mWDB==null || !mWDB.isOpen()){
            mWDB= mHelper.getWritableDatabase();
        }
        return mWDB;
    }


    //创建数据库，执行建表语言
    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql="CREATE TABLE IF NOT EXISTS "+ TABLE_NAME + " (" +
                    "_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"+
                    " user_name VARCHAR NOT NULL,"+
                    " password VARCHAR NOT NULL);";
        db.execSQL(sql);
    }

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

    }

    public long insert(User user){
        ContentValues values=new ContentValues();
        values.put("user_name",user.user_name);
        values.put("password",user.password);
        return mWDB.insert(TABLE_NAME,null,values);
    }

    public long delete(User user){
        String name= user.getName();
        String passwd= user.getPassword();
        return mWDB.delete(TABLE_NAME,"user_name=? and password=?",new String[]{name,passwd});
    }

    //我们查询出来的内容，需要有个容器存放，以供使用，所以定义了一个ArrayList类的list
    //这里使用游标Cursor
    public ArrayList<User> getAllData(){
        ArrayList<User> list = new ArrayList<User>();
        @SuppressLint("Recycle") Cursor cursor = db.query(TABLE_NAME,null,null,null,null,null,null);
        while(cursor.moveToNext()){
            @SuppressLint("Range") String user_name = cursor.getString(cursor.getColumnIndex("user_name"));
            @SuppressLint("Range") String password = cursor.getString(cursor.getColumnIndex("password"));

            list.add(new User(user_name,password));
        }
        return list;
    }
}
