package leigh.tesseract;

import leigh.mecha.cred.Credential;
import leigh.mecha.json.JSONArray;
import leigh.mecha.json.JSONObject;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;

/**
 * Produces {@link HostGroup} objects from stored JSON data.
 *
 * @author Alex Leigh
 */
public class JsonHostGroupReader {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(JsonHostGroupReader.class);

    public HostGroup readHostGroup(String json) throws IOException {
        JSONObject object = new JSONObject(json);
        HostGroup hg = new HostGroup();

        String defaultUser = object.optString("defaultUser");
        String defaultPass = object.optString("defaultPassword");
        hg.setDefaultCredential(new Credential(defaultUser, defaultPass));

        String defaultSshKeyPath = object.optString("defaultSshKeyFile");
        if (!StringUtils.isEmpty(defaultSshKeyPath)) hg.setDefaultSshKey(defaultSshKeyPath);

        JSONArray hosts = object.getJSONArray("hosts");
        if (hosts != null) {

            for (int i = 0; i < hosts.length(); i++) {
                JSONObject host = hosts.getJSONObject(i);
                if (host != null) {
                    String hostname = host.getString("hostname");
                    if (!StringUtils.isBlank(hostname)) {
                        hg.addHost(hostname);
                    }

                    String un = host.optString("username");
                    String pw = host.optString("password");

                    if (!StringUtils.isBlank(un)) {
                        hg.getCreds().putCredential(hostname, new Credential(un, pw));
                    }

                    String ssh = host.optString("sshKeyFile");
                    if (!StringUtils.isEmpty(ssh)) hg.setSshKey(hostname, ssh);
                }
            }
        }

        return hg;
    }
}
