package com.yutou.jianr_mg.Databases;

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

import com.yutou.jianr_mg.Application;
import com.yutou.jianr_mg.Data.User;

public class UserDatabase extends SQLiteOpenHelper {
    private static UserDatabase database;
    private SQLiteDatabase writeDatabase,readDatabase;
    private static String TAB_USER="u_user";
    public static UserDatabase init(){
        if(database==null){
            database=new UserDatabase();
            database.writeDatabase=database.getWritableDatabase();
            database.readDatabase=database.getReadableDatabase();
        }
        return database;
    }

    private UserDatabase() {
        super(Application.application,"userData_db",null,1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql="create table "+TAB_USER+"(_id integer primary key,id integer,uname verchar(50),token verchar(50))";
        db.execSQL(sql);
    }

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

    }
    public void login(int id,String uname,String token){
        deleteTable(TAB_USER);
        Cursor cursor=readDatabase.query(TAB_USER,new String[]{"id","uname"},"id=? and uname=?",new String[]{id+"",uname},null,null,null);
        ContentValues values=new ContentValues();
        values.put("id",id);
        values.put("uname",uname);
        values.put("token",token);
        cursor.moveToFirst();
        if(cursor.getCount() > 0){
            writeDatabase.update(TAB_USER,values,"_id=?",new String[]{1+""});
        }else{
            writeDatabase.insert(TAB_USER,null,values);
        }
        cursor.close();
    }
    public User getUser(){
        Cursor cursor=readDatabase.query(TAB_USER,new String[]{"id,uname,token"},"_id=?",new String[]{"1"},null,null,null);
        User user=null;
       cursor.moveToFirst();
        if(cursor.getCount() > 0){
            user=new User();
            user.setId(cursor.getInt(cursor.getColumnIndex("id")));
            user.setName(cursor.getString(cursor.getColumnIndex("uname")));
            user.setImei("-----");
            user.setPass("-----");
            user.setToken(cursor.getString(cursor.getColumnIndex("token")));
            user.setPower(0);
        }
        cursor.close();
        return user;
    }
    private void deleteTable(String tableName){
        writeDatabase.execSQL("delete from  "+tableName);
    }
}
