package com.sunxung.factoring.start.impl;

import java.io.IOException;
import java.util.List;

import org.springframework.core.io.ClassPathResource;

import com.sunxung.factoring.component.util.SpringUtil;
import com.sunxung.factoring.entity.sys.Permission;
import com.sunxung.factoring.entity.sys.PermissionConfig;
import com.sunxung.factoring.entity.sys.PermissionConfig.PermissionXml;
import com.sunxung.factoring.service.sys.PermissionService;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.XppDriver;

/**
 *  权限字典项初始化
 */
public class PermissionInit {

    private static PermissionService permissionService;

    public void run() throws IOException {
        XStream xs = new XStream(new XppDriver());
        xs.processAnnotations(PermissionConfig.class);
        PermissionConfig permissionConfig = (PermissionConfig) xs
                .fromXML(new ClassPathResource("permissionConfig.xml").getInputStream());
        addPermission(permissionConfig.getPermissionXmls(), null);
    }

    private void addPermission(List<PermissionXml> xmls, Long parentId) {
        if (xmls != null && xmls.size() > 0) {
            for (PermissionXml xml : xmls) {
                Permission permission = getPermissionService().add(createPermissionXml(xml, parentId));
                addPermission(xml.getChildren(), permission.getId());
            }
        }
    }

    private Permission createPermissionXml(PermissionXml xml, Long parentId) {
        Permission permission = new Permission();
        permission.setParentId(parentId);
        permission.setCname(xml.getCname());
        permission.setEname(xml.getEname());
        permission.setGradation(xml.getGradation());
        permission.setModuleName(xml.getModuleName());
        permission.setUrl(xml.getUrl());
        permission.setIcon(xml.getIcon());
        return permission;
    }

    private static PermissionService getPermissionService() {
        if (permissionService == null) {
            permissionService = SpringUtil.getBeanByType(PermissionService.class);
        }
        return permissionService;
    }
}
