package de.thpeetz.kontor.common.views;

import com.vaadin.flow.component.Unit;
import com.vaadin.flow.component.customfield.CustomField;
import com.vaadin.flow.component.select.Select;
import lombok.extern.slf4j.Slf4j;

import de.thpeetz.kontor.comics.data.Comic;
import de.thpeetz.kontor.comics.data.Issue;

import java.util.List;

@Slf4j
public class ComicIssueField extends CustomField<Issue> {

    public final Select<Comic> comic = new Select<>();
    public final Select<Issue> issue = new Select<>();

    public ComicIssueField(String caption) {
        comic.setEnabled(false);
        comic.setWidth(9, Unit.EM);
        comic.setItemLabelGenerator(Comic::getTitle);
        comic.addValueChangeListener(e -> {
            updateIssues();
        });
        issue.setEnabled(false);
        issue.setWidth(9, Unit.EM);
        issue.setItemLabelGenerator(Issue::getIssueNumber);
        add(comic, issue);
    }

    @Override
    protected Issue generateModelValue() {
        log.info("ComicIssueField.generateModelValue: {}", issue.getValue());
        return issue.getValue();
    }

    @Override
    protected void setPresentationValue(Issue newPresentationValue) {
        log.info("ComicIssueField.setPresentationValue({})", newPresentationValue);
        if (newPresentationValue == null) return;
        comic.setValue(newPresentationValue.getComic());
        log.info("setPresentationValue: set Comic select = {}", comic.getValue());
        issue.setValue(newPresentationValue);
    }

    public void setComics(List<Comic> comics) {
        log.info("ComicIssueField.setComics");
        comic.setItems(comics);
        comic.setEnabled(true);
    }

    private void updateIssues() {
        log.info("ComicIssueField.updateIssues");
        if (comic.getValue() == null) {
            issue.setValue(null);
            issue.setEnabled(false);
            return;
        }
        issue.setItems(comic.getValue().getIssues());
        issue.setEnabled(true);
    }
}
