001/*
002 * SPDX-License-Identifier: Apache-2.0
003 *
004 * Copyright 2025-2026 The Enola <https://enola.dev> Authors
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License");
007 * you may not use this file except in compliance with the License.
008 * You may obtain a copy of the License at
009 *
010 *     https://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package dev.enola.tool.todo.cli;
019
020import dev.enola.common.io.mediatype.YamlMediaType;
021import dev.enola.common.io.object.jackson.JacksonObjectReaderWriterChain;
022
023import picocli.CommandLine.Command;
024import picocli.CommandLine.Model.CommandSpec;
025import picocli.CommandLine.ParentCommand;
026import picocli.CommandLine.Spec;
027
028import java.io.IOException;
029import java.util.concurrent.Callable;
030
031@Command(name = "list", description = "List ToDo items")
032public class ToDoListCommand implements Callable<Integer> {
033
034    @ParentCommand ToDoMain parent;
035
036    @Spec CommandSpec spec;
037
038    private final JacksonObjectReaderWriterChain writer = new JacksonObjectReaderWriterChain();
039
040    @Override
041    public Integer call() throws IOException {
042        var hadFailure = false;
043        var yaml = YamlMediaType.YAML_UTF_8;
044        for (var todo : parent.repository.list()) {
045            var opt = writer.write(todo, yaml);
046            if (opt.isPresent()) {
047                spec.commandLine().getOut().println(opt.get());
048            } else {
049                spec.commandLine()
050                        .getErr()
051                        .println("error: failed to serialize ToDo item: " + todo);
052                hadFailure = true;
053            }
054        }
055        return hadFailure ? 1 : 0;
056    }
057}