package jp.gihyo.mitoma.android.p011login;

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

import java.util.ArrayList;

public class MemberDAO  {
    //private Context context;
    private SQLiteDatabase db;
    private static MemberDAO dao = null;
    private MemberDAO(Context context){
        //this.context = context;
        MemberOpenHelper helper = new MemberOpenHelper(context);
        this.db = helper.getWritableDatabase();
    }
    public static MemberDAO getInstance(Context context){
        if( MemberDAO.dao == null){
            MemberDAO.dao = new MemberDAO(context);
        }
        return MemberDAO.dao;
    }
    public ArrayList<MemberDTO> select(){
        ArrayList<MemberDTO> list = new ArrayList<>();
        Cursor cursor = db.query("member", null, null, null, null, null, null);
        while(cursor.moveToNext()){
            String id = cursor.getString(0);
            String name = cursor.getString(1);
            String psw = cursor.getString(2);
            MemberDTO dto = new MemberDTO(id,name,psw);
            list.add(dto);
        }
        cursor.close();
        return list;
    }
    public MemberDTO select(String id){
        MemberDTO dto = null;
        String where = "member_id='" + id + "'" ;
        Cursor cursor = db.query("member", null, where,
                null, null, null, null);
        if(cursor.moveToFirst()){
            String name = cursor.getString(1);
            String psw = cursor.getString(2);
            dto = new MemberDTO(id,name,psw);
        }
        cursor.close();
        return dto;
    }
    public long insert(MemberDTO dto){
        long result = 0;
        ContentValues values = new ContentValues();
        values.put("member_id", dto.memberID);
        values.put("member_name", dto.memberName);
        values.put("password", dto.password);
        result = db.insert("member", null, values);
        return result;
    }
}
