/*
 * Copyright 2012 astamuse company,Ltd.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */

package com.astamuse.asta4d.util;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class MultiSearchPathResourceLoader<T> {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private String[] searchPathList = new String[0];

    public MultiSearchPathResourceLoader() {
    }

    public T searchResource(String pathSeparator, String... names) {
        if (names == null || names.length < 1) {
            throw new IllegalArgumentException("must specify one or more names");
        }
        return searchResource(pathSeparator, -1, names);
    }

    private T searchResource(String pathSeparator, int index, String... names) {
        List<String> searchNames = new ArrayList<>();
        for (String name : names) {
            String searchName;
            if (index < 0) {
                searchName = name;
            } else if (index >= searchPathList.length) {
                logger.debug("Did not find any associated resource for name {}", name);
                return null;
            } else {
                String searchPath = searchPathList[index];
                boolean pathWithSeparator = searchPath.endsWith(pathSeparator);
                boolean nameWithSeparator = name.startsWith(pathSeparator);
                if (pathWithSeparator && nameWithSeparator) {
                    searchName = searchPath + name.substring(1);
                } else if (pathWithSeparator || nameWithSeparator) {
                    searchName = searchPath + name;
                } else { // nether has
                    searchName = searchPath + pathSeparator + name;
                }
            }
            logger.debug("try load resource for {}", searchName);
            T result = loadResource(searchName);
            if (result != null) {
                return result;
            }
            searchNames.add(searchName);
        }
        logger.debug("load resource for {} failed", searchNames.toString());
        return searchResource(pathSeparator, index + 1, names);
    }

    protected abstract T loadResource(String name);

    public String[] getSearchPathList() {
        return searchPathList.clone();
    }

    public void setSearchPathList(String... searchPathList) {
        this.searchPathList = searchPathList.clone();
    }

}
