namespace Nerfed.Builder;

public static class FileUtil
{
    public static void Copy(FileInfo srcFile, FileInfo dstFile)
    {
        Copy(srcFile.FullName, dstFile.FullName);
    }

    public static void Copy(string srcFile, string dstFile)
    {
        string dstDir = Path.GetDirectoryName(dstFile);
        if (!Directory.Exists(dstDir))
        {
            Directory.CreateDirectory(dstDir);
        }

        File.Copy(srcFile, dstFile, true);
        UpdateFileTimeAttributes(dstFile);
    }

    public static void WriteBytes(string dstFile, byte[] bytes)
    {
        File.WriteAllBytes(dstFile, bytes);
        UpdateFileTimeAttributes(dstFile);
    }

    public static void UpdateFileTimeAttributes(string file)
    {
        // Copy over date time attributes so we can check if the file changed.
        FileInfo dstFileInfo = new FileInfo(file);
        DateTime now = DateTime.Now;
        DateTime utcNow = DateTime.UtcNow;
        dstFileInfo.CreationTime = now;
        dstFileInfo.CreationTimeUtc = utcNow;
        dstFileInfo.LastWriteTime = now;
        dstFileInfo.LastWriteTimeUtc = utcNow;
        dstFileInfo.LastAccessTime = now;
        dstFileInfo.LastAccessTimeUtc = utcNow;
    }

    /// <summary>
    /// True if the inFileInfo is newer than the outFileInfo.
    /// </summary>
    public static bool IsNewer(FileInfo inFileInfo, FileInfo outFileInfo)
    {
        return !outFileInfo.Exists || outFileInfo.LastWriteTime <= inFileInfo.LastWriteTime;
    }
}
