package com.example.petstoremobile.viewmodels;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.petstoremobile.dtos.DropdownDTO;
import com.example.petstoremobile.dtos.EmployeeDTO;
import com.example.petstoremobile.repositories.EmployeeRepository;
import com.example.petstoremobile.repositories.StoreRepository;
import com.example.petstoremobile.utils.Resource;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import dagger.hilt.android.lifecycle.HiltViewModel;

@HiltViewModel
public class StaffDetailViewModel extends ViewModel {
    private final EmployeeRepository repository;
    private final StoreRepository storeRepository;
    private final MutableLiveData<List<DropdownDTO>> storeList = new MutableLiveData<>(new ArrayList<>());
    private long employeeId = -1;
    private boolean isEditing = false;

    @Inject
    public StaffDetailViewModel(EmployeeRepository repository, StoreRepository storeRepository) {
        this.repository = repository;
        this.storeRepository = storeRepository;
    }

    public LiveData<Resource<List<DropdownDTO>>> loadStores() {
        return storeRepository.getStoreDropdowns();
    }

    public LiveData<List<DropdownDTO>> getStoreList() {
        return storeList;
    }

    public void setStoreList(List<DropdownDTO> list) {
        storeList.setValue(list);
    }

    public LiveData<Resource<EmployeeDTO>> loadEmployee(long id) {
        return repository.getEmployeeById(id);
    }

    public void setEmployeeId(long id, boolean isEditing) {
        this.employeeId = id;
        this.isEditing = isEditing;
    }

    public long getEmployeeId() {
        return employeeId;
    }

    public boolean isEditing() {
        return isEditing;
    }

    public EmployeeDTO createEmployeeDto(String username, String password, String firstName,
                                        String lastName, String email, String phone,
                                        String role, String staffRole, boolean active, Long storeId) {
        EmployeeDTO dto = new EmployeeDTO(username, password, firstName, lastName, email, phone, role, staffRole, active, storeId);
        dto.setFullName(firstName + " " + lastName);
        return dto;
    }

    public LiveData<Resource<EmployeeDTO>> saveEmployee(EmployeeDTO dto) {
        if (isEditing && employeeId > 0) {
            return repository.updateEmployee(employeeId, dto);
        } else {
            return repository.createEmployee(dto);
        }
    }

    public LiveData<Resource<Void>> deleteEmployee() {
        return repository.deleteEmployee(employeeId);
    }
}
