package me.chyxion.tigon.form;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

/**
 * @version 0.0.1
 * @since 0.0.1
 * @author Shaun Chyxion <br>
 * chyxion@163.com <br>
 * Oct 8, 2016 5:27:20 PM
 */
@Slf4j
public class BaseForm implements BaseFormApi {
    private static final long serialVersionUID = 1L;

    /**
     * clone to class
     * @param clazz copy to class
     * @return copy result
     */
    @Override
    public <T> T copy(Class<T> clazz) {
        return copy(clazz, false);
    }

    /**
     * copy to class
     * @param clazz copy to class
     * @param convert true to convert fields
     * @return copy result
     */
    @Override
    public <T> T copy(Class<T> clazz, boolean convert) {
        log.debug("Copy Form [{}] To Class [{}].", this, clazz);
        T obj = null;
        try {
            obj = clazz.newInstance();
        }
        catch (Exception e) {
            throw new IllegalStateException(
                "Create [" + clazz + "] Object Error Caused", e);
        }
        return copy(obj, convert);
    }

    /**
     * copy to object
     * @param obj copy to object
     * @return copy result
     */
    @Override
    public <T> T copy(T obj) {
        return copy(obj, false);
    }

    /**
     * copy props with converting
     * @param obj copy to object
     * @param convert true to convert object fields
     * @return copy result object
     */
    @Override
    public <T> T copy(T obj, boolean convert) {
        try {
            if (convert) {
                log.debug("Copy Form [{}] To [{}] With Type Converting.", this, obj);
                org.apache.commons.beanutils.BeanUtils.copyProperties(obj, this);
            }
            else {
                log.debug("Copy Form [{}] To [{}].", this, obj);
                BeanUtils.copyProperties(this, obj);
            }
            return obj;
        }
        catch (Exception e) {
            throw new IllegalStateException(
                "Copy [" + this + "] Error Caused", e);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}
