package jp.gihyo.mitoma.android.lesson01_07;

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

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class FriendsByFileDAO {
    private static String FILE_NAME = "friends.txt";
    private File file;
    public FriendsByFileDAO(Context context){
       this.file = new File(context.getFilesDir(), FILE_NAME);
    }
    public FriendsDTO select(String id){
        FriendsDTO dto = null;
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] items=line.split(",");
                if(id.equals(items[0])) {
                    dto = new FriendsDTO(items[0], items[1], items[2]);
                    break;
                }
            }
        }catch(IOException e){
            e.printStackTrace();
        }
        return dto;
    }
    public long insert(FriendsDTO dto){
        long result = 1;
        String record = dto.id + "," + dto.name + "," + dto.tel;
        try(BufferedWriter bw = new BufferedWriter(new FileWriter(file,true))){
            bw.write(record);
            bw.newLine();
            bw.flush();
            bw.close();
        }catch(IOException e){
            e.printStackTrace();
            result = -1;
        }
        return result;
    }
}
