--!A cross-platform build utility based on Lua
--
-- 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.
--
-- Copyright (C) 2015-present, Xmake Open Source Community.
--
-- @author      ruki
-- @file        find_directory.lua
--

-- define module
local sandbox_lib_detect_find_directory = sandbox_lib_detect_find_directory or {}

-- load modules
local os        = require("base/os")
local path      = require("base/path")
local utils     = require("base/utils")
local table     = require("base/table")
local raise     = require("sandbox/modules/raise")
local vformat   = require("sandbox/modules/vformat")
local xmake     = require("base/xmake")

-- expand search paths
function sandbox_lib_detect_find_directory._expand_paths(paths)
    local results = {}
    for _, _path in ipairs(table.wrap(paths)) do
        local _path = _path
        if type(_path) == "function" then
            local ok, result_or_errors = sandbox.load(_path)
            if ok then
                _path = result_or_errors or ""
            else
                raise(result_or_errors)
            end
        else
            _path = vformat(_path)
        end
        for _, _s_path in ipairs(table.wrap(_path)) do
            local _s_path = tostring(_s_path)
            if #_s_path > 0 then
                table.insert(results, _s_path)
            end
        end
    end
    return results
end

-- normalize suffixes
function sandbox_lib_detect_find_directory._normalize_suffixes(suffixes)
    local results = {}
    for _, suffix in ipairs(table.wrap(suffixes)) do
        local suffix = tostring(suffix)
        if #suffix > 0 then
            table.insert(results, suffix)
        end
    end
    return results
end

-- find directory from directories list
function sandbox_lib_detect_find_directory._find_from_directories(name, directories, suffixes)
    directories = table.wrap(directories)
    suffixes = table.wrap(suffixes)
    if #suffixes > 0 then
        for _, directory in ipairs(directories) do
            for _, suffix in ipairs(suffixes) do
                local results = os.dirs(path.join(directory, suffix, name), function (file, isdir) return false end)
                if results and #results > 0 then
                    return results[1]
                end
            end
        end
    else
        for _, directory in ipairs(directories) do
            local results = os.dirs(path.join(directory, name), function (file, isdir) return false end)
            if results and #results > 0 then
                return results[1]
            end
        end
    end
end

-- find directory
--
-- @param name      the directory name
-- @param paths     the search paths (e.g. dirs, paths, winreg paths)
-- @param opt       the options, e.g. {suffixes = {"/aa", "/bb"}}
--
-- @return          the directory path
--
-- @code
--
-- local dir = find_directory("bin", { "/usr", "/usr/local"})
-- local dir = find_directory("xxx/test", { "/usr/include", "/usr/local/include/**"})
-- local dir = find_directory("xxx/test", { "$(env PATH)", "$(reg HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\XXXX;Name)"})
-- local dir = find_directory("xxx/test/dir*", { "$(env PATH)", function () return val("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\XXXX;Name"):match("\"(.-)\"") end})
--
-- @endcode
--
function sandbox_lib_detect_find_directory.main(name, paths, opt)

    -- init options
    opt = opt or {}

    local suffixes = sandbox_lib_detect_find_directory._normalize_suffixes(opt.suffixes)
    local directories = sandbox_lib_detect_find_directory._expand_paths(paths)

    if opt.async and xmake.in_main_thread() then
        local result, _ = os._async_task().find_directory(name, directories, {suffixes = suffixes})
        return result
    end

    return sandbox_lib_detect_find_directory._find_from_directories(name, directories, suffixes)
end

-- return module
return sandbox_lib_detect_find_directory

