package eu.eudat.elastic.entities;

import org.elasticsearch.common.xcontent.XContentBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by ikalyvas on 7/5/2018.
 */
public class Dataset implements ElasticEntity<Dataset> {
    private static final Logger logger = LoggerFactory.getLogger(Dataset.class);

    public enum Status {
        SAVED((short) 0), FINALISED((short) 1), CANCELED((short) 2), DELETED((short) 99),;

        private short value;

        private Status(short value) {
            this.value = value;
        }

        public short getValue() {
            return value;
        }

        public static Status fromInteger(int value) {
            switch (value) {
                case 0:
                    return SAVED;
                case 1:
                    return FINALISED;
                case 2:
                    return CANCELED;
                case 99:
                    return DELETED;
                default:
                    throw new RuntimeException("Unsupported Dataset Status");
            }
        }
    }

    private String id;
    private List<Tag> tags = new LinkedList<>();
    private String label;
    private String description;
    private UUID template;
    private Short status;
    private UUID dmp;
    private UUID group;
    private UUID grant;
    private List<Collaborator> collaborators;
    private Boolean lastVersion;
    private Boolean lastPublicVersion;
    private List<Organization> organizations;
    private Boolean isPublic;
    private Short grantStatus;
    private String formData;
    private Date created;
    private Date modified;
    private Date finalizedAt;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public List<Tag> getTags() {
        return tags;
    }

    public void setTags(List<Tag> tags) {
        this.tags = tags;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public UUID getTemplate() {
        return template;
    }

    public void setTemplate(UUID template) {
        this.template = template;
    }

    public Short getStatus() {
        return status;
    }

    public void setStatus(Short status) {
        this.status = status;
    }

    public UUID getDmp() {
        return dmp;
    }

    public void setDmp(UUID dmp) {
        this.dmp = dmp;
    }

    public UUID getGroup() {
        return group;
    }

    public void setGroup(UUID group) {
        this.group = group;
    }

    public UUID getGrant() {
        return grant;
    }

    public void setGrant(UUID grant) {
        this.grant = grant;
    }

    public List<Collaborator> getCollaborators() {
        return collaborators;
    }

    public void setCollaborators(List<Collaborator> collaborators) {
        this.collaborators = collaborators;
    }

    public Boolean getLastVersion() {
        return lastVersion;
    }

    public void setLastVersion(Boolean lastVersion) {
        this.lastVersion = lastVersion;
    }

    public Boolean getLastPublicVersion() {
        return lastPublicVersion;
    }

    public void setLastPublicVersion(Boolean lastPublicVersion) {
        this.lastPublicVersion = lastPublicVersion;
    }

    public List<Organization> getOrganizations() {
        return organizations;
    }

    public void setOrganizations(List<Organization> organizations) {
        this.organizations = organizations;
    }

    public Boolean getPublic() {
        return isPublic;
    }

    public void setPublic(Boolean aPublic) {
        isPublic = aPublic;
    }

    public Short getGrantStatus() {
        return grantStatus;
    }

    public void setGrantStatus(Short grantStatus) {
        this.grantStatus = grantStatus;
    }

    public String getFormData() {
        return formData;
    }

    public void setFormData(String formData) {
        this.formData = formData;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public Date getModified() {
        return modified;
    }

    public void setModified(Date modified) {
        this.modified = modified;
    }

    public Date getFinalizedAt() {
        return finalizedAt;
    }

    public void setFinalizedAt(Date finalizedAt) {
        this.finalizedAt = finalizedAt;
    }

    @Override
    public XContentBuilder toElasticEntity(XContentBuilder builder) throws IOException {
        builder.startObject();
        builder.field("id", this.id);
        builder.field("label", this.label);
        builder.field("description", this.description);
        builder.field("template", this.template.toString());
        builder.field("status", this.status.toString());
        builder.field("dmp", this.dmp.toString());
        builder.field("created", this.created);
        builder.field("modified", this.modified);
        builder.field("finalizedAt", this.finalizedAt);
        if (this.group != null) {
            builder.field("group", this.group.toString());
        }
        builder.field("grant", this.grant.toString());
        if (collaborators != null) {
            builder.startArray("collaborators");
            this.collaborators.forEach(x -> {
                try {
                    x.toElasticEntity(builder);
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }

            });
            builder.endArray();
        }
        builder.field("lastVersion", this.lastVersion.toString());
        builder.field("lastPublicVersion", this.lastPublicVersion.toString());
        if (organizations != null) {
            builder.startArray("organizations");
            this.organizations.forEach(x -> {
                try {
                    x.toElasticEntity(builder);
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }

            });
            builder.endArray();
        }
        if (this.tags != null) {
            builder.startArray("tags");
            this.tags.forEach(x -> {
                try {
                    x.toElasticEntity(builder);
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            });
            builder.endArray();
        }
        if (this.isPublic != null) {
            builder.field("public", this.isPublic.toString());
        }
        if (this.grantStatus != null) {
            builder.field("grantStatus", this.grantStatus.toString());
        }
        builder.field("formData", this.formData);
        builder.endObject();
        return builder;
    }

    @Override
    public Dataset fromElasticEntity(Map<String, Object> fields) {
        if (fields != null) {
            if (fields.size() == 1) {
                if (fields.containsKey("id")) {
                    this.id = (String) fields.get("id");
                } else if (fields.containsKey("tags")) {
                    this.tags = ((List<HashMap>) fields.get("tags")).stream().map(hashMap -> new Tag().fromElasticEntity(hashMap)).collect(Collectors.toList());
                }
            }else if (fields.size() > 1) {
                this.id = (String) fields.get("id");
                if (fields.get("tags") != null) {
                    this.tags = ((List<HashMap>) fields.get("tags")).stream().map(hashMap -> new Tag().fromElasticEntity(hashMap)).collect(Collectors.toList());
                }
                this.label = (String) fields.get("label");
                this.description = (String) fields.get("description");
                this.template = UUID.fromString((String) fields.get("template"));
                this.status = Short.valueOf((String) fields.get("status"));
                this.dmp = UUID.fromString((String) fields.get("dmp"));
                this.group = UUID.fromString((String) fields.get("group"));
                this.grant = UUID.fromString((String) fields.get("grant"));
                if (fields.get("created") != null)
                    this.created = Date.from(Instant.parse((String) fields.get("created")));
                if (fields.get("modified") != null)
                    this.modified = Date.from(Instant.parse((String) fields.get("modified")));
                if (fields.get("finalizedAt") != null)
                    this.finalizedAt = Date.from(Instant.parse((String) fields.get("finalizedAt")));
                if (fields.get("collaborators") != null) {
                    this.collaborators = ((List<HashMap>) fields.get("collaborators")).stream().map(hashMap -> new Collaborator().fromElasticEntity(hashMap)).collect(Collectors.toList());
                }
                this.lastVersion = Boolean.parseBoolean((String) fields.get("lastVersion"));
                this.lastPublicVersion = Boolean.parseBoolean((String) fields.get("lastPublicVersion"));
                if (fields.get("organizations") != null) {
                    this.organizations = ((List<HashMap>) fields.get("organizations")).stream().map(hashMap -> new Organization().fromElasticEntity(hashMap)).collect(Collectors.toList());
                }
                if (fields.get("public") != null) {
                    this.isPublic = Boolean.valueOf((String) fields.get("public"));
                }
                if (fields.get("grantStatus") != null) {
                    this.grantStatus = Short.valueOf((String) fields.get("grantStatus"));
                }
                this.formData = (String) fields.get("formData");
            }
        }
        return this;
    }

}
