UpdateCommand.java

package org.docascode.api;

import org.docascode.api.core.office.CheckBoxProcessor;
import org.docascode.api.core.office.table.Table;
import org.docascode.api.core.errors.DocAsCodeException;
import org.docascode.api.core.office.Properties;
import org.docascode.api.core.office.table.TableProcessor;
import org.docascode.api.event.Event;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UpdateCommand extends DocAsCodeCommand<Map<String, Map<String, String>>> {
    public enum Action {
        ADD,
        LIST
    }

    private Action action = Action.ADD;

    private List<File> files;

    private Map<String,String> properties = new HashMap<>();

    private List<String> delete = new ArrayList<>();

    private List<Table> tables = new ArrayList<>();

    private Map<String,Boolean> checkboxes = new HashMap<>();

    public UpdateCommand setAction(Action action){
        this.action = action;
        return this;
    }

    public UpdateCommand setFiles(List<File> files){
        this.files = files;
        return this;
    }

    public UpdateCommand setProperties(Map<String,String> map){
        this.properties = map;
        return this;
    }

    public UpdateCommand deleteProperties(List<String> keys){
        this.delete = keys;
        return this;
    }

    public UpdateCommand setTables(List<Table> tables){
        this.tables = tables;
        return this;
    }

    public UpdateCommand setCheckboxes(Map<String,Boolean> checkboxes){
        this.checkboxes.putAll(checkboxes);
        return this;
    }

    @Override
    public Map<String, Map<String, String>> call() throws DocAsCodeException {
        Map<String, Map<String, String>> result = new HashMap<>();
        if (this.action == Action.LIST) {
            result = Properties.list(files);
        } else {
            for (File file : this.files) {
                log(String.format("Updating file '%s'.", file), Event.Level.INFO);
                for (String key : delete) {
                    log(String.format("\tdelete %s", key), Event.Level.INFO);
                }
                Properties.delete(file, delete);
                for (Map.Entry<String, String> m : properties.entrySet()) {
                    log(String.format("\t%s:'%s'", m.getKey(), m.getValue()), Event.Level.INFO);
                }
                Properties.set(file, properties);
                for (Table t : this.tables) {
                    TableProcessor.insertRow(file, t);
                }
                CheckBoxProcessor checkBoxProcessor = new CheckBoxProcessor();
                checkBoxProcessor.addListener(this);
                for (Map.Entry<String, Boolean> m : checkboxes.entrySet()) {
                    checkBoxProcessor.setStatus(file, m.getKey(), m.getValue());
                }
            }
        }
        return result;
    }
}