package jp.gihyo.mitoma.android.lesson2301sqlite;

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

import java.util.ArrayList;

public class FriendsDAO {
    private Context context;
    private SQLiteDatabase db;
    private String table = "friends";
    // コンストラクタ
    public FriendsDAO(Context context){
        this.context = context;
        FriendsOpenHelper helper = new FriendsOpenHelper(context);
        this.db = helper.getWritableDatabase();
    }
    // 全件抽出
    public ArrayList<FriendsDTO> select(){
        ArrayList<FriendsDTO> list = new ArrayList<FriendsDTO>();
        Cursor cursor = db.query(table, null, null, null, null, null, null);
        while(cursor.moveToNext()){
            int id = cursor.getInt(0);
            String name = cursor.getString(1);
            String tel = cursor.getString(2);
            String memo = cursor.getString(3);
            FriendsDTO  dto = new FriendsDTO(id,name,tel,memo);
            list.add(dto);
        }
        cursor.close();
        return list;
    }
    // 1件抽出
    public FriendsDTO select(int id){
        FriendsDTO dto = null;
        String[] columns ={"id","name","tel","memo"};
        String where = "id=?";
        String[] selectionArgs ={String.valueOf(id)};
        Cursor cursor = db.query(table, columns, where,
                selectionArgs, null, null, null);
        if(cursor.moveToFirst()){
            String name = cursor.getString(1);
            String tel = cursor.getString(2);
            String memo = cursor.getString(3);
            dto = new FriendsDTO(id,name,tel,memo);
        }
        cursor.close();
        return dto;
    }
    // 追加
    public long insert(FriendsDTO dto){
       long ret;
        ContentValues values = new ContentValues();
        values.put("name", dto.name);
        values.put("tel", dto.tel);
        values.put("memo", dto.memo);
        ret = db.insert(table, null, values);
        return ret;
    }
    // 更新
    public int update(FriendsDTO dto){
        int result = 0;
        ContentValues values = new ContentValues();
        values.put("name", dto.name);
        values.put("tel", dto.tel);
        values.put("memo", dto.memo);
        String whereClause = "id = ?";
        String[] whereArgs = {String.valueOf(dto.id)};
        result = db.update(table,values,whereClause, whereArgs  );
        return result;
    }
    // 削除
    public int delete(int id){
        int result = 0;
        String whereClause = "id = ?";
        String[] whereArgs = {String.valueOf(id)};
        result = db.delete(table,whereClause, whereArgs);
        return result;
    }

}
