package com.ecep.contract.controller.employee;

import java.util.HashMap;
import java.util.List;

import org.springframework.data.domain.Pageable;

import com.ecep.contract.controller.tab.TabSkin;
import com.ecep.contract.model.Employee;
import com.ecep.contract.model.EmployeeRole;

import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.collections.ListChangeListener;
import javafx.scene.control.ListCell;
import javafx.scene.control.Tab;

public class EmployeeTabSkinRole
        extends AbstEmployeeBasedTabSkin
        implements TabSkin {

    private final SimpleBooleanProperty changed = new SimpleBooleanProperty(false);

    public EmployeeTabSkinRole(EmployeeWindowController controller) {
        super(controller);
    }

    @Override
    public BooleanProperty changeProperty() {
        return changed;
    }

    @Override
    public Tab getTab() {
        return controller.rolesTab;
    }

    @Override
    public void initializeTab() {
        initializeListView();
        loadSelectedRoles();
    }

    private void loadSelectedRoles() {
        List<EmployeeRole> selectedRoles = getEmployeeService().getRolesByEmployeeId(viewModel.getId().get());
        controller.rolesField.getTargetItems().setAll(selectedRoles);
        changed.set(false);
    }

    private void initializeListView() {
        // 非系统内置账户
        HashMap<String, Object> params = new HashMap<>();
        List<EmployeeRole> roles = getEmployeeRoleService().findAll(params, Pageable.ofSize(500)).getContent();

        controller.rolesField.getSourceItems().setAll(roles);
        controller.rolesField.setCellFactory(param -> {
            return new ListCell<>() {
                @Override
                protected void updateItem(EmployeeRole item, boolean empty) {
                    super.updateItem(item, empty);
                    if (item == null || empty) {
                        setText(null);
                    } else {
                        setText(item.getName());
                    }
                }
            };
        });

        controller.rolesField.getTargetItems().addListener((ListChangeListener<EmployeeRole>) change -> {
            while (change.next()) {
                List<? extends EmployeeRole> added = change.getAddedSubList();
                List<? extends EmployeeRole> removed = change.getRemoved();
                if (!added.isEmpty() || !removed.isEmpty()) {
                    changed.set(true);
                }
            }
        });
    }

    @Override
    public void save() {
        Employee entity = getEntity();
        entity.setRoles(controller.rolesField.getTargetItems());
        save(entity);
        loadSelectedRoles();
    }
}
