package org.iri_research.renkan.forms;

import java.io.Serializable;

import org.iri_research.renkan.RenkanException;
import org.iri_research.renkan.models.IRenkanColoredModel;
import org.iri_research.renkan.repositories.IRenkanRepository;

public abstract class RenkanForm<ID extends Serializable, RM extends IRenkanColoredModel<ID>> {

    protected RM model;

    private ID id;
    private String title;
    private String description;
    private String uri;
    private String color;

    protected abstract void saveToModel();

    protected abstract IRenkanRepository<RM, ID> getRepository();

    protected abstract RM getModelInstance();

    public RenkanForm() {
    }

    public RenkanForm(RM model) {
        if (model == null) {
            return;
        }
        this.model = model;
        this.id = model.getId();
        this.title = model.getTitle();
        this.description = model.getDescription();
        this.color = model.getColor();
        this.uri = model.getUri();
    }

    public ID getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

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

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public void setModel(RM model) {
        this.model = model;
    }

    private void saveToRenkanModel() {

        this.model.setTitle(title);
        this.model.setDescription(description);
        this.model.setColor(color);
        this.model.setUri(uri);
    }

    public RM save() throws RenkanException {

        if (this.model == null) {

            if (this.getId() != null) {
                this.model = this.getRepository().findOne(this.getId());
                if (this.model == null) {
                    throw new RenkanException("Model id "
                            + this.getId().toString() + " not found");
                }
            } else {
                this.model = this.getModelInstance();
            }
        }

        this.saveToRenkanModel();
        this.saveToModel();

        this.model = this.getRepository().save(this.model);

        return this.model;

    }

}
