package com.ym.mec.util.excel;

import com.ym.mec.util.exception.UtilException;
import org.ini4j.Ini;
import org.ini4j.InvalidFileFormatException;
import org.ini4j.Profile.Section;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.Map.Entry;

public class IniFileUtil {

    /**
     * 读取Ini文件
     *
     * @param iniFile 文件绝对路径(文件编码须UTF-8)
     * @return 返回所有section以及下面的key/value
     * @throws InvalidFileFormatException
     * @throws IOException
     */
    public static Map<String, List<IniFileEntity>> readIniFile(File iniFile) throws InvalidFileFormatException, IOException {
        if (!iniFile.exists()) {
            throw new UtilException("文件[" + iniFile.getAbsolutePath() + "]不存在");
        }
        Ini ini = new Ini();
        ini.load(iniFile);

        Map<String, List<IniFileEntity>> result = new HashMap<String, List<IniFileEntity>>();
        IniFileEntity entity = null;

        Collection<Section> sections = ini.values();
        for (Section section : sections) {
            List<IniFileEntity> entryList = result.get(section.getName());
            if (entryList == null) {
                entryList = new ArrayList<IniFileEntity>();
            }
            for (Entry<String, String> entry : section.entrySet()) {
                entity = new IniFileEntity();
                entity.setSection(section.getName());
                entity.setKey(entry.getKey());
                entity.setValue(entry.getValue());

                entryList.add(entity);
            }
            result.put(section.getName(), entryList);
        }

        return result;
    }


    /**
     * 读取Ini文件
     *
     * @param inputStream
     * @return 返回所有section以及下面的key/value
     * @throws InvalidFileFormatException
     * @throws IOException
     */
    public static Map<String,String> readIniFile(InputStream inputStream,String fileName) throws InvalidFileFormatException, IOException {
        Ini ini = new Ini();
        try {
            ini.load(inputStream);
        } catch (Exception e) {
            throw new UtilException(e.getMessage());
        } finally {
            inputStream.close();
        }

//        Collection<Section> sections = ini.values();
        Section section = ini.get(fileName);
//        for (Section section : sections) {
        Map<String,String> map = new HashMap<>(section.entrySet().size());
        for (Entry<String, String> entry : section.entrySet()) {
            map.put(entry.getKey(),entry.getValue());
        }
        return map;
//        }
//        return new HashMap<>();
    }
}
