package com.brframework.commoncms.utils;

import com.brframework.common.utils.PackageUtil;
import com.brframework.commoncms.core.layout.PanelLayoutColumn;
import com.brframework.commoncms.core.layout.column.LayoutTextColumn;
import com.google.common.collect.Lists;

import java.lang.reflect.Field;
import java.util.List;

/**
 * 列工具
 * @author xu
 * @date 2018/10/9 17:09
 */
public class LayoutColumnUtil {

    /**
     * 列所在包名
     */
    public static final String GROUP_COLUMN_PACKAGE = "com.ns.cms.core.layout.column";

    private static final List<PanelLayoutColumn> layoutColumns;
    static  {
        layoutColumns = Lists.newArrayList();
        List<Class<?>> layoutColumnClassList = PackageUtil.getClass(GROUP_COLUMN_PACKAGE, true);
        for (Class<?> lcc : layoutColumnClassList) {
            try {

                if(PanelLayoutColumn.class.isAssignableFrom(lcc)){
                    layoutColumns.add((PanelLayoutColumn) lcc.newInstance());
                }

            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取默认支持的列
     * @param field
     * @return
     */
    public static PanelLayoutColumn defaultColumn(Field field){

        for (PanelLayoutColumn layoutColumn : layoutColumns) {
            if(layoutColumn.isSupportType(field.getType())){
                try {
                    return layoutColumn.getClass().newInstance();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }

        return new LayoutTextColumn();

    }

}
