package uk.gov.openregister.model;

import com.fasterxml.jackson.databind.JsonNode;
import org.apache.commons.lang3.text.WordUtils;

import java.util.Optional;

public class Field {

    String name;
    String friendlyName;
    Datatype datatype;
    Cardinality cardinality;
    Optional<String> register;

    public Field(JsonNode node) {

        name = Optional.of(node.get("field")).map(JsonNode::asText).get();
        friendlyName = Optional.ofNullable(node.get("name")).map(JsonNode::asText).orElse(WordUtils.capitalize(name));
        datatype = Optional.ofNullable(node.get("datatype")).map(d -> Datatype.of(d.asText())).orElse(Datatype.DEFAULT);
        cardinality = Optional.ofNullable(node.get("cardinality")).map(c -> Cardinality.fromValue(c.textValue())).orElse(Cardinality.ONE);
        register = Optional.ofNullable(node.get("register")).map(JsonNode::asText).filter(s -> !s.isEmpty() && !"null".equals(s));
    }

    public Field(String name) {
        this.name = name;
        this.friendlyName = WordUtils.capitalize(name);
        this.datatype = Datatype.DEFAULT;
        this.cardinality = Cardinality.ONE;
        this.register = Optional.empty();
    }

    public Field(String name, Cardinality cardinality) {
        this.name = name;
        this.friendlyName = WordUtils.capitalize(name);
        this.datatype = Datatype.DEFAULT;
        this.cardinality = cardinality;
        this.register = Optional.empty();
    }

    public Field(String name, String friendlyName, Datatype datatype, Cardinality cardinality, Optional<String> register) {
        this.name = name;
        this.friendlyName = friendlyName;
        this.datatype = datatype;
        this.cardinality = cardinality;
        this.register = register;
    }

    public String getName() {
        return name;
    }

    public String getFriendlyName() {
        return friendlyName;
    }

    public Datatype getDatatype() {
        return datatype;
    }

    public Cardinality getCardinality() {
        return cardinality;
    }

    public Optional<String> getRegister() {
        return register;
    }
}

@@ -235,24 +235,43 @@
 ype datatype
+ = Datatype.DEFAULT
 ;%0A    Cardin
@@ -283,24 +283,42 @@
  cardinality
+ = Cardinality.ONE
 ;%0A    Option
@@ -336,16 +336,35 @@
 register
+ = Optional.empty()
 ;%0A%0A    p
@@ -1103,142 +1103,14 @@
 e);%0A
-        this.datatype = Datatype.DEFAULT;%0A        this.cardinality = Cardinality.ONE;%0A        this.register = Optional.empty();%0A
     %7D%0A
+
 %0A   
@@ -1262,117 +1262,33 @@
 his.
-datatype = Datatype.DEFAULT;%0A        this.cardinality = cardinality;%0A        this.register = Optional.empty()
+cardinality = cardinality
 ;%0A  

simplify code by using field defaults