package com.huigou.uasp.bmp.opm.application.impl;

import com.huigou.uasp.bmp.opm.application.CssIconParser;
import com.huigou.uasp.bmp.opm.domain.model.resource.Icon;
import cz.vutbr.web.css.CSSException;
import cz.vutbr.web.css.CSSFactory;
import cz.vutbr.web.css.RuleSet;
import cz.vutbr.web.css.StyleSheet;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 解析 Font Awesome css文件来获取菜单图片。
 *
 * @author yonghuan
 */
public class FontAwesomeCssIconParser implements CssIconParser {

    @Override
    public boolean supports(String source) {
        return true;
    }

    @Override
    public Collection<Icon> parse(String source) throws IOException {
        String css = Files.readAllLines(Paths.get(source))
                .stream()
                .collect(Collectors.joining("\n"));
        StyleSheet sheet;
        try {
            sheet = CSSFactory.parseString(css, null);
        } catch (IOException | CSSException e) {
            throw new IllegalArgumentException("解析font awesome css图标出错", e);
        }
        return sheet.stream().filter(block -> block instanceof RuleSet)
                .map(RuleSet.class::cast)
                .filter(rule -> rule.getSelectors().length == 1)
                .filter(rule -> rule.size() == 1)
                .filter(rule -> "content".equals(rule.get(0).getProperty()))
                .map(rule -> rule.getSelectors()[0].get(0).getClassName())
                .map(className -> new Icon(className, String.format("<i class='fa %s'></i>", className)))
                .collect(Collectors.toList());
    }
}
