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

namespace Plesk\MigrationLibV8\MailImport\Backend\Files;

use Plesk\MigrationLibV8\Plesk\PleskFunctions;
use Plesk\MigrationLibV8\Utils\FileUtils;

class MigrationList
{
    private $_migrationListFilePath;

    /**
     * MigrationList constructor.
     * @param string $migrationListFilePath
     */
    public function __construct($migrationListFilePath)
    {
        $this->_migrationListFilePath = $migrationListFilePath;
    }

    /**
     * @param \Plesk\MigrationLibV8\MailImport\Entity\ImportOperation\MailAddressPair[] $mailAddressPairs
     */
    public function write($mailAddressPairs)
    {
        $siteMigrationListContents = [
            'mail_address_pairs' => [],
        ];

        foreach ($mailAddressPairs as $mailAddressPair) {
            if ($mailAddressPair->getSourcePassword() === null) {
                $sourcePassword = null;
            } else {
                $sourcePassword = PleskFunctions::encryptPassword($mailAddressPair->getSourcePassword());
            }
            if ($mailAddressPair->getTargetPassword() === null) {
                $targetPassword = null;
            } else {
                $targetPassword = PleskFunctions::encryptPassword($mailAddressPair->getTargetPassword());
            }

            $siteMigrationListContents['mail_address_pairs'][] = [
                'source_email' => $mailAddressPair->getSourceEmail(),
                'source_password' => $sourcePassword,
                'target_mailname' => $mailAddressPair->getTargetMailname(),
                'target_password' => $targetPassword,
                'imap_host' => $mailAddressPair->getImapHost(),
                'imap_port' => $mailAddressPair->getImapPort(),
                'ignore_security_warnings' => $mailAddressPair->getIgnoreSecurityWarnings(),
                'imap_encryption' => $mailAddressPair->getImapEncryption(),
                'imap_timeout' => $mailAddressPair->getImapTimeout(),
                'imap_folder_separator' => $mailAddressPair->getImapFolderSeparator()
            ];
        }

        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;
    }
}
