<?php

use Joomla\Filesystem\Exception\FilesystemException;
use Joomla\Filesystem\File;
use Joomla\Filesystem\Folder;
use Joomla\Filesystem\Path;

final class WatchfulliFileHelper
{
    public static function exists(string $path): bool
    {
        if (version_compare(WatchfulliJoomlaVersion::getVersion(), '3.10', '<')) {
            return JFile::exists($path);
        }

        return is_file(Path::clean($path));
    }

    public static function write(string $file, string $buffer): bool
    {
        if (version_compare(WatchfulliJoomlaVersion::getVersion(), '3.10', '<')) {
            return JFile::write($file, $buffer);
        }

        return File::write($file, $buffer);
    }

    public static function delete(string $file): bool
    {
        if (version_compare(WatchfulliJoomlaVersion::getVersion(), '3.10', '<')) {
            return JFile::delete($file);
        }

        if (self::exists($file) === false) {
            return true;
        }

        try {
            return File::delete($file);
        } catch (FilesystemException $e) {
            watchfulli::debug($e->getMessage());
            return false;
        }
    }

    public static function move(string $source, string $destination): bool
    {
        if (version_compare(WatchfulliJoomlaVersion::getVersion(), '3.10', '<')) {
            return JFile::move($source, $destination);
        }

        return File::move($source, $destination);
    }

    public static function getExt(string $file): string
    {
        if (version_compare(WatchfulliJoomlaVersion::getVersion(), '3.10', '<')) {
            return JFile::getExt($file);
        }

        if (version_compare(WatchfulliJoomlaVersion::getVersion(), '5.0', '<')) {
            return \Joomla\CMS\Filesystem\File::getExt($file);
        }

        return File::getExt($file);
    }

    public static function folderExists(string $path): bool
    {
        return @is_dir($path);
    }

    public static function copyFolder($src, $dest): bool
    {
        if (version_compare(WatchfulliJoomlaVersion::getVersion(), '3.10', '<')) {
            return JFolder::copy($src, $dest);
        }

        return Folder::copy($src, $dest, '', true);
    }

	public static function isWindows(): bool
	{
		return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
	}
}