package me.chyxion.tigon.service.support;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import me.chyxion.tigon.model.BaseModel;
import me.chyxion.tigon.model.ViewModel;
import me.chyxion.tigon.mybatis.BaseMapper;
import me.chyxion.tigon.form.BaseFormForCreateApi;
import me.chyxion.tigon.form.BaseFormForUpdateApi;
import me.chyxion.tigon.service.BaseCrudByFormService;

/**
 * @version 0.0.1
 * @since 0.0.1
 * @author Shaun Chyxion <br>
 * chyxion@163.com <br>
 * May 16, 2016 3:28:54 PM
 */
@Slf4j
public class BaseCrudByFormServiceSupport
    <PrimaryKey, Model extends BaseModel<PrimaryKey>,
        FormForCreate extends BaseFormForCreateApi,
        FormForUpdate extends BaseFormForUpdateApi<PrimaryKey>,
        Mapper extends BaseMapper<PrimaryKey, Model>>
    extends BaseCrudServiceSupport<PrimaryKey, Model, Mapper>
    implements BaseCrudByFormService<PrimaryKey, Model, FormForCreate, FormForUpdate> {

    /**
     * {@inheritDoc}
     */
    @Override
    public ViewModel<Model> create(FormForCreate form) {
        log.debug("Create Form [{}].", form);
        validate(form);
        return create(form.copy(modelType));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ViewModel<Model> update(FormForUpdate form) {
        validate(form);
        PrimaryKey primaryKey = form.getId();
        Model model = find(primaryKey);
        Assert.state(model != null, "No Model [" + primaryKey + "] Found");
        return update(form.copy(model));
    }
    

    // -- 
    // private methods

    /**
     * validate create form
     * @param form create form
     */
    protected void validate(FormForCreate form) {
        // For Override
    }
    
    /**
     * validate update form
     * @param form update form
     */
    protected void validate(FormForUpdate form) {
        // For Override
    }
}
