package jp.gihyo.mitoma.android.lesson2402contentprov;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class FriendsAction {
    private Activity act;
    public FriendsAction(Activity act){
        this.act = act;
    }
    public void exec(View view){
        EditText etId = act.findViewById(R.id.etId);
        EditText etName = act.findViewById(R.id.etName);
        EditText etTel = act.findViewById(R.id.etTel);
        EditText etMemo = act.findViewById(R.id.etMemo);
        int id = Integer.parseInt(etId.getText().toString());
        String name = etName.getText().toString();
        String tel = etTel.getText().toString();
        String memo = etMemo.getText().toString();
        long returnNo;

        String tag = view.getTag().toString();
        FriendsProvDAO ds = new FriendsProvDAO((Context)act);
        FriendsDTO dto = new FriendsDTO();

        switch(tag){
            case "REGISTER":
                dto = new FriendsDTO(0,name,tel,memo);
                returnNo = ds.insert(dto);
                dto.id = (int)returnNo;
                Toast.makeText(act,"登録完了 登録番号="+returnNo,Toast.LENGTH_LONG).show();

                break;
            case "ENQUIRY":
                dto = ds.select(id);
                if(dto == null) {
                    dto.id = id;
                    dto.name = "(該当レコード無し)";
                }
                Toast.makeText(act, "照会完了", Toast.LENGTH_LONG).show();
                break;
            case "UPDATE":
                dto = new FriendsDTO(id,name,tel,memo);
                returnNo = ds.update(dto);
                if(returnNo== 0) {
                    Toast.makeText(act, "該当レコード無し", Toast.LENGTH_LONG).show();
                }
                Toast.makeText(act, "更新完了", Toast.LENGTH_LONG).show();
                break;
            case "DELETE":
                returnNo = ds.delete(id);
                if(returnNo == 0) {
                    dto.id = id;
                    dto.name = "該当レコード無し";
                }else{
                    dto.name = "";
                    dto.tel = "";
                    dto.memo = "";
                }
                Toast.makeText(act, "削除完了", Toast.LENGTH_LONG).show();
                break;
        }
        etId.setText(String.valueOf(dto.id));
        etName.setText(dto.name);
        etTel.setText(dto.tel);
        etMemo.setText(dto.memo);
    }

}
