<?php

namespace DropshippingExportFreeVendor\WPDesk\Library\DropshippingExport\Service\Writer;

use Exception;
class FileLocker
{
    private Generator $generator;
    public function __construct(Generator $generator)
    {
        $this->generator = $generator;
    }
    public function flush(string $file_path, bool $create_new_file): void
    {
        $lock_file = $file_path . '.lock';
        $lock_handle = null;
        $lock_acquired = \false;
        $timeout = 30;
        $start_time = time();
        while (time() - $start_time < $timeout) {
            if (file_exists($lock_file)) {
                $lock_age = time() - filemtime($lock_file);
                if ($lock_age > 60) {
                    unlink($lock_file);
                }
            }
            $lock_handle = fopen($lock_file, 'w');
            if ($lock_handle === \false) {
                sleep(1);
                continue;
            }
            if (flock($lock_handle, \LOCK_EX | \LOCK_NB)) {
                fwrite($lock_handle, time());
                $lock_acquired = \true;
                break;
            } else {
                fclose($lock_handle);
                $lock_handle = null;
                sleep(1);
            }
        }
        if (!$lock_acquired) {
            throw new Exception('Could not acquire file lock for: ' . $file_path . ' after ' . $timeout . ' seconds');
        }
        try {
            $this->generator->flush_batch($file_path, $create_new_file);
        } finally {
            if ($lock_handle !== null) {
                flock($lock_handle, \LOCK_UN);
                fclose($lock_handle);
                unlink($lock_file);
            }
        }
    }
}
