package cn.ibizlab.codegen.templating;

import cn.ibizlab.codegen.model.CliData;
import cn.ibizlab.codegen.model.CliOption;
import cn.ibizlab.codegen.model.ModelStorage;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.springframework.util.StringUtils;

import java.nio.file.Paths;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Getter
@Setter
@NoArgsConstructor
@Accessors(chain = true)
public class TemplateDefinition {
    private String templateFile;

    protected TemplateFileType templateType;

    private String subType;

    protected CliData templateDatas;

    public TemplateDefinition(String templateFile) {
        if (templateFile == null) throw new IllegalArgumentException("templateFile may not be null.");

        this.templateFile = templateFile;
        this.templateType = getType(Paths.get(this.templateFile));
        CliData data=ModelStorage.getInstance().getTemplateData(this.templateType);
        if(StringUtils.isEmpty(subType))
            this.templateDatas = data;
        else
            this.templateDatas = data.getSubData(subType);
    }


    private TemplateFileType getType(Path path)
    {
        if(path==null)
            return TemplateFileType.supportingFiles;

        if(StringUtils.isEmpty(path.getFileName()))
            return TemplateFileType.supportingFiles;
        String fileName=path.getFileName().toString();
        for(TemplateFileType type:TemplateFileType.values())
        {
            Pattern p = Pattern.compile("\\{\\{([^}]*)\\}\\}");
            Matcher m = p.matcher(fileName);
            while (m.find()) {
                String[] pairs=m.group(1).split("@");
                if(type.name().equalsIgnoreCase(pairs[0])
                        ||type.value().equalsIgnoreCase(pairs[0])
                        ||type.name().endsWith(" "+pairs[0])
                        ||type.value().endsWith(" "+pairs[0])
                        ||type.name().startsWith(pairs[0]+".")
                        ||type.value().startsWith(pairs[0]+".")
                ) {
                    if(pairs.length>1&&(!StringUtils.isEmpty(pairs[1])))
                        this.setSubType(pairs[1]);
                    return type;
                }
            }

        }
        return getType(path.getParent());
    }

}
