package jp.gihyo.mitoma.android.lesson2301sqlite;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

import java.util.ArrayList;


public class FriendsProvDAO {
    private Context context;
    private ContentResolver resolver;
     public FriendsProvDAO(Context context){
        this.context = context;
        this.resolver = context.getContentResolver();
    }
    public ArrayList<FriendsDTO> select(){
        ArrayList<FriendsDTO> list = new ArrayList<FriendsDTO>();
        Cursor cursor = resolver.query(FriendsProvider.CONTENT_URI,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;
    }
    public FriendsDTO select(int id){
        FriendsDTO dto = null;
        String[] columns ={"id","name","tel","memo"};
        String where = "id=?";
        String[] selectionArgs ={String.valueOf(id)};
        Cursor cursor = resolver.query(FriendsProvider.CONTENT_URI,columns, where,
                selectionArgs, 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 = -1;
        ContentValues values = new ContentValues();
        values.put("name", dto.name);
        values.put("tel", dto.tel);
        values.put("memo", dto.memo);
        Uri uri = resolver.insert(FriendsProvider.CONTENT_URI, values);
        Cursor cursor = resolver.query(uri, null, null, null, "id DESC");
        if(cursor.moveToFirst()){
            ret = cursor.getLong(0);
        }
        cursor.close();
        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 = resolver.update(FriendsProvider.CONTENT_URI, values,whereClause, whereArgs);
        return result;
    }
    public int delete(int id){
        int result = 0;
        String whereClause = "id = ?";
        String[] whereArgs = {String.valueOf(id)};
        result = resolver.delete(FriendsProvider.CONTENT_URI,whereClause, whereArgs);
        return result;
    }

}
