package jp.gihyo.mitoma.android.s1602listview;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView listView = findViewById(R.id.lvFriends);
        //
        FriendsDS friendsDS = FriendsDS.getInstance();
        ArrayList<FriendsDTO> friendList = friendsDS.select();

        //イメージデータ作成
        ArrayList<Integer> imageList = new ArrayList<>();
        int i = 0;
        for (FriendsDTO dto : friendList) {
            if (dto.id.charAt(0) == 'F') imageList.add(i, R.drawable.droid1);
            if (dto.id.charAt(0) == 'S') imageList.add(i, R.drawable.droid2);
            if (dto.id.charAt(0) == 'W') imageList.add(i, R.drawable.droid3);
            i++;
        }
        //カスタムアダプタ生成
        FriendsAdapter adapter = new FriendsAdapter(
                this, R.layout.custom_layout02, friendList, imageList);
        listView.setAdapter(adapter);
        // 行にクリックリスナーをセット
        listView.setOnItemClickListener(new MyClickListener());
    }

    private class MyClickListener implements AdapterView.OnItemClickListener{
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            FriendsDTO dto = (FriendsDTO)parent.getItemAtPosition(position);
            ListView listView = findViewById(R.id.lvFriends);
            boolean checked = listView.isItemChecked(position);

            if(checked){
                Toast.makeText(MainActivity.this,dto.name + "さんが選択されました",Toast.LENGTH_LONG).show();
            }else{
                Toast.makeText(MainActivity.this,dto.name + "さんが選択解除されました",Toast.LENGTH_LONG).show();
            }
        }
    }
}