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

namespace Plesk\MigrationLibV8\MailImport;

class SessionFiles extends \Plesk\MigrationLibV8\Common\SessionFiles
{
    /**
     * Get full path to file with the mail migration status.
     *
     * The file contains status of migration (in progress, success, failure, etc) for each mail address pair,
     * and list of import issues for each mail address pair.
     *
     * @param string|null $taskId get status file for specific mail import task;
     * when not specified global status is returned
     * @return string
     * @throws \Exception when specified task ID is invalid
     */
    public function getStatusFilePath($taskId=null)
    {
        if (is_null($taskId)) {
            return $this->_session->getPath() . DIRECTORY_SEPARATOR . 'mail_migration_status.json';
        } else {
            $tasksDir = $this->_session->getPath() . DIRECTORY_SEPARATOR . 'tasks';

            $allTasks = [];
            foreach (new \DirectoryIterator($tasksDir) as $file) {
                if ($file->isDir()) {
                    $allTasks[] = $file->getFilename();
                }
            }

            if (!in_array($taskId, $allTasks)) {
                throw new \Exception("Invalid task specified");
            }


            return $tasksDir . DIRECTORY_SEPARATOR . $taskId . DIRECTORY_SEPARATOR . 'task-status.json';
        }
    }

    /**
     * Get full path to file with the mail migration list.
     *
     * @param $suffix
     * @return string
     */
    public function getMailMigrationListPath($suffix)
    {
        if (!is_null($suffix)) {
            $filename = "mail_migration_list_{$suffix}.json";
        } else {
            $filename = 'mail_migration_list.json';
        }
        return $this->_session->getPath() . DIRECTORY_SEPARATOR . $filename;
    }
}
