package jp.gihyo.mitoma.android.p014gdpmanagement;

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

public class CountryAction {
    private Activity act;
    private static final String TAG ="CountryAction";
    public CountryAction(Activity act){
        this.act = act;
    }
    public void exec(View view) {
        EditText etCno = act.findViewById(R.id.etCno);
        EditText etCname = act.findViewById(R.id.etCname);
        EditText etGDP = act.findViewById(R.id.etGDP);
        EditText etPop = act.findViewById(R.id.etPop);
        int cNo = Integer.parseInt(etCno.getText().toString());
        String name = etCname.getText().toString();
        double gdp = Double.parseDouble(etGDP.getText().toString());
        double pop = Double.parseDouble(etPop.getText().toString());
        String tag = view.getTag().toString();
        CountryDAO dao = CountryDAO.getInstance((Context)act);
        Log.i(TAG,"View TAG:" + tag);
        if (tag.equals("REGISTER")) {

            CountryDTO dto = new CountryDTO(cNo, name, gdp, pop);
            dao.insert(dto);
            Toast.makeText(act, "登録完了", Toast.LENGTH_LONG).show();

        } else if (tag.equals("ENQUIRY")) {
            CountryDTO dto = dao.select(cNo);
            if (dto != null) {
                etCname.setText(dto.countryName);
                etGDP.setText(String.valueOf(dto.gdp));
                etPop.setText(String.valueOf(dto.population));
            } else {
                etCname.setText("(該当データ無し)");
                etGDP.setText("");
                etPop.setText("");
            }
            Toast.makeText(act, "照会完了", Toast.LENGTH_LONG).show();

        } else if (tag.equals("UPDATE")) {
            CountryDTO dto = new CountryDTO(cNo, name, gdp, pop);
            dao.update(dto);
            Toast.makeText(act, "更新完了", Toast.LENGTH_LONG).show();

        } else if (tag.equals("DELETE")) {
            dao.delete(cNo);
            Toast.makeText(act, "削除完了", Toast.LENGTH_LONG).show();
        }
    }
}
