package com.example.tampopo_client.viewmodels;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import java.lang.reflect.InvocationTargetException;

/**
 * ViewModelのライフサイクルの関係で、インスタンスを生成するためのFactoryクラスが必要
 *
 * @author Shohei Yamagiwa
 */
public class ActivityViewModelFactory implements ViewModelProvider.Factory {
    private final String userId;
    private final String token;

    public ActivityViewModelFactory(String userId, String token) {
        this.userId = userId;
        this.token = token;
    }

    @NonNull
    @Override
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        if (modelClass.isAssignableFrom(ActivityViewModel.class)) {
            try {
                return modelClass.getConstructor(String.class, String.class).newInstance(userId, token);
            } catch (InvocationTargetException | IllegalAccessException | InstantiationException |
                     NoSuchMethodException e) {
                throw new RuntimeException(e);
            }
        }
        throw new IllegalStateException("作成するViewModelが異なります。");
    }
}
