﻿using Dossier.Internal.Rollbacks;
using System;
using System.IO;

namespace Dossier.Internal.Operations
{
    internal class MoveDirectoryOperation : OperationBase
    {
        public MoveDirectoryOperation(ITransaction transaction, string sourcePath, string destinationPath)
            : base(transaction, OperationType.MoveDirectory)
        {
            _sourcePath = Path.GetFullPath(sourcePath);
            _destinationPath = Path.GetFullPath(destinationPath);
        }

        public MoveDirectoryOperation(ITransaction transaction, Guid uid, string sourcePath, string destinationPath)
            : base(transaction, OperationType.MoveDirectory, uid)
        {
            _sourcePath = Path.GetFullPath(sourcePath);
            _destinationPath = Path.GetFullPath(destinationPath);
        }

        public override void Execute()
        {
            if (Directory.Exists(_destinationPath))
            {
                if (_transaction != null)
                {
                    _rollback = RollbackFactory.GetRollback(this, _destinationPath);
                }

                Directory.Delete(_destinationPath);
            }
            Directory.Move(_sourcePath, _destinationPath);
            _isExecuted = true;
        }

        public override void Reverse()
        {
            if (_isExecuted && _transaction != null)
            {
                if (Directory.Exists(_destinationPath))
                {
                    // move the directory back to it's original location
                    Directory.Move(_destinationPath, _sourcePath);
                }

                if (_rollback != null)
                {
                    // there was a directory at the destination path
                    // which we over-wrote, so write back the
                    // original contents
                    _rollback.Write(_destinationPath);
                }
            }
        }
    }
}
