package DX::Lib::FS::Action::RewriteFile;

use DX::Lib::FS::Fact::FileContent;
use Moo;

with 'DX::Role::Action';
with 'DX::Lib::FS::Role::RunOn';

has from => (is => 'ro', required => 1, handles => [ 'path' ]);

has add_lines => (is => 'ro', default => sub { [] });

has remove_lines => (is => 'ro', default => sub { [] });

has final_content => (is => 'lazy', init_arg => undef, builder => sub {
  my ($self) = @_;
  my %remove = map +($_ => 1), @{$self->remove_lines};
  join("\n",
    (grep !$remove{$_}, $self->from->lines->all),
    @{$self->add_lines},
    ''
  );
});

sub but_add {
  $_[0]->but(add_lines => [ @{$_[0]->add_lines}, $_[1] ]);
}

sub but_remove {
  $_[0]->but(remove_lines => [ @{$_[0]->remove_lines}, $_[1] ]);
}

sub expected_effect {
  my ($self) = @_;
  +(file_content => DX::Lib::FS::Fact::FileContent->new(
    path => $self->path,
    data => $self->final_content
  ));
}

sub _do_run {
  my ($self) = @_;
  $self->_call_guts(rewrite_file => $self->final_content);
  return +(file_content => $self->path);
}

1;
