package org.academiadecodigo.bootcamp.model;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * MIT License
 * (c) 2017 Ricardo Constantino
 */

public class Bootcamp {
    private Integer id;
    private BootcampLocation location;
    private Date start;
    private Date end;
    private Set<CodeCadet> cadets;
    private final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");

    public Bootcamp(Integer id, BootcampLocation location, String start, String end) {
        this.id = id;
        this.location = location;
        setStart(start);
        setEnd(end);
        this.cadets = new HashSet<>();
    }

    public boolean contains(CodeCadet codeCadet) {
        return cadets.contains(codeCadet);
    }

    public void addCodeCadet(CodeCadet codeCadet) {
        codeCadet.setBootcamp(this);
        cadets.add(codeCadet);
    }

    public Set<CodeCadet> getCadets() {
        return cadets;
    }

    public Integer getId() {
        return id;
    }

    public String getLocation() {
        return location.name();
    }

    public String getStart() {
        return start != null ? dateFormat.format(start) : "TBD";
    }

    public String getEnd() {
        return end != null ? dateFormat.format(end) : "TBD";
    }

    public void setStart(Date start) {
        this.start = start;
    }

    public void setEnd(Date end) {
        this.end = end;
    }

    public void setStart(String start) {
        try {
            if (start == null) {
                return;
            }
            this.start = dateFormat.parse(start);
        } catch (ParseException e) {
            this.start = null;
        }
    }

    public void setEnd(String end) {
        try {
            if (end == null) {
                return;
            }
            this.end = dateFormat.parse(end);
        } catch (ParseException e) {
            this.end = null;
        }
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder("{");
        res.append("Bootcamp #").append(id).append(", ");
        res.append("Location: ").append(location).append(", ");
        res.append("Start: ").append(start != null ? dateFormat.format(start) : "TBD").append(", ");
        res.append("End: ").append(end != null ? dateFormat.format(end) : "TBD");

        return res.append("}").toString();
    }

    public enum BootcampLocation {
        LISBOA,
        FUNDÃO,
        TERCEIRA;
    }
}
