package eu.eudat.models.data.external;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class ProjectsExternalSourcesModel extends ExternalListingItem<ProjectsExternalSourcesModel> {
	private static final Logger logger = LoggerFactory.getLogger(ProjectsExternalSourcesModel.class);
	private static final ObjectMapper mapper = new ObjectMapper();

	@Override
	public ProjectsExternalSourcesModel fromExternalItem(List<Map<String, String>> values) {
		for (Map<String, String> item : values) {
			ExternalSourcesItemModel model = new ExternalSourcesItemModel();
			try {
				JsonNode node = mapper.readTree(mapper.writeValueAsBytes(item));
				JsonNode name = node.get("name");
				if (name != null && !name.isNull() && name.isObject()) {
					model.setName(node.get("name").get("$").asText());
				} else {
					model.setName((String)item.get("name"));
				}

				JsonNode pid = node.get("pid");
				if (pid != null && !pid.isNull() && pid.isObject()) {
					model.setRemoteId(node.get("pid").get("$").asText());
				} else {
					model.setRemoteId((String)item.get("pid"));
				}

				JsonNode uri = node.get("uri");
				if (uri != null && !uri.isNull() && uri.isObject()) {
					model.setUri(node.get("uri").get("$").asText());
				} else {
					model.setUri((String)item.get("uri"));
				}

				JsonNode description = node.get("description");
				if (description != null && !description.isNull() && description.isObject()) {
					model.setDescription(node.get("description").get("$").asText());
				} else {
					model.setDescription((String)item.get("description"));
				}

				JsonNode tag = node.get("tag");
				if (tag != null && !tag.isNull() && tag.isObject()) {
					model.setTag(node.get("tag").get("$").asText());
				} else {
					model.setTag((String)item.get("tag"));
				}

				JsonNode key = node.get("key");
				if (key != null && !key.isNull() && key.isObject()) {
					model.setKey(node.get("key").get("$").asText());
				} else {
					model.setKey((String)item.get("key"));
				}

				this.add(model);

			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
		return this;
	}
}
