<?php
// Copyright 1999-2017. Plesk International GmbH. All rights reserved.

namespace Plesk\MigrationLibV8\SiteImport\Backend\Files;

use Plesk\MigrationLibV8\Utils\FileUtils;

class MigrationList
{
    private $_migrationListFilePath;

    public function __construct($migrationListFilePath)
    {
        $this->_migrationListFilePath = $migrationListFilePath;
    }

    /**
     * @param \Plesk\MigrationLibV8\SiteImport\Entity\ImportOperation\Application[] $applications
     * @param \Plesk\MigrationLibV8\SiteImport\Entity\ImportOperation\Folder[] $folders
     * @param \Plesk\MigrationLibV8\SiteImport\Entity\ImportOperation\Database[] $databases
     * @param string $command
     */
    public function write($applications, $folders, $databases, $command)
    {
        $siteMigrationListContents = [
            'filter_applications' => [],
            'include_files' => [],
            'include_databases' => []
        ];

        foreach ($applications as $application) {
            $siteMigrationListContents['filter_applications'][] = [
                'type' => $application->getType(),
                'source_path' => $application->getSourcePath(),
                'target_path' => $application->getTargetPath()
            ];
        }

        foreach ($folders as $folder) {
            $siteMigrationListContents['include_files'][] = [
                'source_path' => $folder->getSourcePath(),
                'target_path' => $folder->getTargetPath()
            ];
        }

        foreach ($databases as $database) {
            $siteMigrationListContents['include_databases'][] = [
                'host' => $database->getHost(),
                'port' => $database->getPort(),
                'username' => $database->getUsername(),
                'password' => $database->getPassword(),
                'name' => $database->getName()
            ];
        }

        $siteMigrationListContents['task'] = $command;

        FileUtils::putFileContents(
            $this->getFilePath(),
            \Zend_Json::prettyPrint(\Zend_Json::encode($siteMigrationListContents))
        );
    }

    /**
     * Get full path to file with the migration list.
     *
     * @return string
     */
    public function getFilePath()
    {
        return $this->_migrationListFilePath;
    }
}
