<?php

/*
 * @author TRYDEA - 2024
 */

namespace Webapp\FileManagement\Service;

use Shared\Authentication\Entity\Site;
use Symfony\Component\Filesystem\Filesystem;
use Webapp\FileManagement\Dto\Mobile\XmlWithFiles;
use Webapp\FileManagement\Exception\WritingException;

/**
 * @final
 */
class WebappWriterService
{
    private WebappXmlWriterService $webappXmlWriterService;
    private string $tmpDir;

    public function __construct(
        WebappXmlWriterService $webappXmlWriterService,
        string $tmpDir
    ) {
        $this->webappXmlWriterService = $webappXmlWriterService;
        $this->tmpDir = $tmpDir;
    }

    /**
     * @param string[] $datas
     *
     * @throws WritingException
     */
    public function createVariableCollectionFile(Site $site, array $datas): \SplFileObject
    {
        $tmpFile = (new Filesystem())->tempnam($this->tmpDir, 'wws-');
        $tmpWorkDir = $this->createWorkDir($tmpFile);

        $xmlWithFiles = $this->webappXmlWriterService->generateVariables($site, $datas, $tmpWorkDir);

        return $this->createVariablesZipFile($xmlWithFiles, $tmpFile, $tmpWorkDir);
    }

    private function createWorkDir(string $tmpFile): string
    {
        $workDir = $tmpFile.'-workdir';
        (new Filesystem())->mkdir($workDir);

        return $workDir;
    }

    /**
     * Create the zip file.
     *
     * @throws WritingException
     */
    private function createVariablesZipFile(XmlWithFiles $xmlWithFiles, string $tmpFile, string $tmpWorkDir): \SplFileObject
    {
        $fs = new Filesystem();

        // Generate temp file for Zip.
        if (empty($xmlWithFiles->getFiles())) {
            // No additional file is present
            $tmpFile .= '.xml';
            file_put_contents($tmpFile, $xmlWithFiles->getXml());

            return new \SplFileObject($tmpFile);
        }

        $tmpFile .= '.zip';

        // Generate temp workdir

        $fs->mkdir($tmpWorkDir);

        // Generate Zip archive
        $zipFile = new \ZipArchive();
        if (true === $zipFile->open($tmpFile, \ZipArchive::CREATE)) {
            // Add the scale item pictures to the zip file
            foreach ($xmlWithFiles->getFiles() as $key => $scaleItemFile) {
                $content = file_get_contents($scaleItemFile);
                $fileDirname = \dirname($tmpWorkDir.'/'.$key);
                $fs->mkdir($fileDirname);

                file_put_contents($tmpWorkDir.'/'.$key, $content);
                $zipFile->addFile($tmpWorkDir.'/'.$key, $key);
            }

            // Add XML variables file
            $tmpXmlPath = $tmpWorkDir.'/transfert.xml';
            file_put_contents($tmpXmlPath, $xmlWithFiles->getXml());
            $zipFile->addFile($tmpXmlPath, 'transfert.xml');
            $zipFile->close();
        } else {
            throw new WritingException('Unable to create zip file');
        }

        // Remove workdir
        $fs->remove($tmpWorkDir);

        return new \SplFileObject($tmpFile);
    }
}
