package Config::Model::Backend::Dpkg::Patch;

use strict;
use warnings;
use Mouse;

extends 'Config::Model::Backend::Any';

with 'Config::Model::Backend::DpkgSyntax';
with 'Config::Model::Backend::DpkgStoreRole';

use 5.20.1;

use feature qw/postderef signatures/;
no warnings qw/experimental::postderef experimental::signatures/;

use Carp;
use Config::Model::Exception;
use Log::Log4perl qw(get_logger :levels);
use Path::Tiny;

my $logger = get_logger("Backend::Dpkg::Patch");

sub skip_open { 1;}

# TODO: use a role provided by Config::Model
sub cfg_path {
    my $self = shift;
    my %args = @_;
    my $cfg_dir   = $args{config_dir};
    my $dir
        = $args{root}   ? path($args{root})->child($cfg_dir)
        : ref($cfg_dir) ? $cfg_dir
        :                 path( $cfg_dir);
    return $dir;
}

sub read {
    my $self = shift;
    my %args = @_;

    # args is:
    # object     => $obj,         # Config::Model::Node object
    # root       => './my_test',  # fake root directory, userd for tests
    # config_dir => /etc/foo',    # absolute path
    # file       => 'foo.conf',   # file name
    # file_path  => './my_test/etc/foo/foo.conf'
    # io_handle  => $io           # IO::File object
    # check      => yes|no|skip

    # io_handle is not defined as no file is specified in model

    my $cfg_dir   = $args{config_dir};
    my $patch_dir = $self->cfg_path(%args);

    my $check     = $args{check};
    my $node      = $args{object};

    my $backend_arg = $self->instance->backend_arg;
    my $patch_name = $node->index_value || $backend_arg;

    my $patch_file = $patch_dir->child($patch_name) ;
    $self->{patch_file} = $patch_file;

    $logger->info("Parsing patch $patch_file");

    my ( $header, $diff ) = ( [],[] );
    my $target = $header;
    foreach my $l ( $patch_file->lines_utf8 ) {
        if ( $l =~ /^---/ ) {
            # beginning of quilt style patch
            $target = $diff;
        }
        elsif ( $l =~ /^===/ ) {
            # beginning of git diff style patch
            push @$diff, pop @$header if $target eq $header;    # get back the Index: line
            $target = $diff;
        }
        push @$target, $l;
    }
    chomp @$header;

    my $c = [] ;
    $logger->trace("header: @$header") ;
    my %stuff ;
    my $store_stuff = sub {
        my ($l,$nb) = @_;
        die "undef line nb" unless defined $nb;
        $stuff{$nb} = $l ;
    } ;

    if (@$header) {
        $c = eval { $self->parse_dpkg_lines( $patch_file, $header, $check, 0, $store_stuff ); };
        my $e = $@;
        if ( ref($e) and $e->isa('Config::Model::Exception::Syntax') ) {
            $e->parsed_file( $patch_file->stringify );
            $e->rethrow;
        }
        elsif (ref($e)) {
            $e->rethrow;
        }
        elsif ($e) {
            die $e;
        }

        Config::Model::Exception::Syntax->throw(
            message => "More than 2 sections in $patch_name header",
            parsed_file => $patch_file->stringify,
        )
          if @$c > 4; # $c contains [ line_nb, section_ref ]
    }

    my $description_holder;
    my @description_text ;
    while (@$c) {
        my ( $section_line, $section ) = splice @$c, 0, 2;
        foreach ( my $i = 0 ; $i < $#$section ; $i += 2 ) {
            my $key = $section->[$i];
            my $v_ref = $section->[ $i + 1 ];
            if ( my $found = $node->find_element( $key, case => 'any' ) ) {
                my $elt = $found ;
                my $to_store = $v_ref;
                if ($found =~ /^Subject|Description$/) {
                    $description_holder = $found;
                    $elt = 'Synopsis';
                    $to_store = [ shift $v_ref->@* ];
                    push @description_text, $v_ref->@*;
                }

                my $elt_obj = $node->fetch_element($elt);
                if ($node->element_type($elt) eq 'list') {
                    $self->store_section_list_element ( $logger, $elt_obj, $check, $to_store);
                }
                else {
                    $self->store_section_leaf_element ( $logger, $elt_obj, $check, $to_store);
                }
            }
            else {
                $stuff{$section_line} = "$key: ".join("\n", map {$_->[0]} $v_ref->@*)."\n";
            }
        }
    }

    my $k = 0;
    push @description_text,''; # force a newline between description and salvaged lines

    # add salvaged lines in the order they were found
    push @description_text, map { [$stuff{$_}, $_, ''] } sort { $a <=> $b ;} keys %stuff ;

    $description_holder //= 'Description';
    my $elt_obj = $node->fetch_element($description_holder);
    $self->store_section_leaf_element ( $logger, $elt_obj, $check, \@description_text);

    # at last, save the "meat" of the patch
    $node->fetch_element('diff')->store(join('',@$diff));

    return 1;
}

sub write {
    my $self = shift;
    my %args = @_;

    # args is:
    # object     => $obj,         # Config::Model::Node object
    # root       => './my_test',  # fake root directory, userd for tests
    # config_dir => /etc/foo',    # absolute path
    # file       => 'foo.conf',   # file name
    # file_path  => './my_test/etc/foo/foo.conf'
    # io_handle  => $io           # IO::File object

    # io_handle is not defined as no file is specified in model

    my $check     = $args{check};
    my $node      = $args{object};

    my $patch_file =     $self->{patch_file} ;
    $logger->info("Writing patch $patch_file");

    my $io = $patch_file->openw_utf8 || Config::Model::Exception::Syntax->throw(
        message => "cannot write patch $patch_file"
    );

    # first: write Description or Subject (where the subuject body is written
    # outside the structured part -- as required by dep-3)
    my $synopsis         = $node->fetch_element_value('Synopsis') || "";
    my $description_body = $node->fetch_element_value('Description') ;
    my $subject_body     = $node->fetch_element_value('Subject') ;

    if ($description_body and $subject_body) {
        die "Write error: cannot have both Subject body and description body";
    }
    elsif ($description_body) {
        my $to_write = $synopsis . "\n" . $description_body ;
        $io->print("Description: ");
        $self->write_dpkg_text($io, $to_write) ;
    }
    elsif ($subject_body) {
        # DEP-3: When Subject is used, it is expected that the
        # long description is outside of the structured
        # fields.
        $io->print("Subject: ");
        $self->write_dpkg_text($io, $synopsis) ;
    }
    else {
        # no description body, write only synopsis
        $io->print("Description: ");
        $self->write_dpkg_text($io, $synopsis) ;
    }

    # second: write all headers
    foreach my $elt ( $node -> get_element_name ) {
        my $elt_obj = $node->fetch_element($elt) ;
        my $type = $node->element_type($elt) ;

        my @v = $type eq 'list' ? $elt_obj->fetch_all_values
              : $type eq 'leaf' ? ($elt_obj->fetch)
              : ();

        foreach my $v (@v) {
            # say "write $elt -> $v" ;
            next unless defined $v and $v;
            next if grep {$elt eq $_} qw/Description Subject Synopsis diff/;

            $io->print("$elt: ");
            $self->write_dpkg_text($io,$v) ;
        }
    }

    # third: write subect body
    if ($subject_body) {
        $io->print($subject_body."\n");
    }

    $io->print($node->fetch_element_value('diff')) ;
    $io->close;

    return 1;
}

1;

__END__

=head1 NAME

Config::Model::Backend::Dpkg::Patch - Read and write Debian Dpkg Patch information

=head1 SYNOPSIS

No synopsis. This class is dedicated to configuration class C<Dpkg::Patch>

=head1 DESCRIPTION

This module is used directly by L<Config::Model> to read or write the
content of Debian C<Patch> file.

All C<Patch> files keyword are read in a case-insensitive manner.

=head1 CONSTRUCTOR

=head2 new ( node => $node_obj, name => 'Dpkg::Patch' ) ;

Inherited from L<Config::Model::Backend::Any>. The constructor will be
called by L<Config::Model::AutoRead>.

=head2 read ( io_handle => ... )

Of all parameters passed to this read call-back, only C<io_handle> is
used. This parameter must be L<IO::File> object already opened for
read. 

It can also be undef. In this case, C<read()> will return 0.

When a file is read,  C<read()> will return 1.

=head2 write ( io_handle => ... )

Of all parameters passed to this write call-back, only C<io_handle> is
used. This parameter must be L<IO::File> object already opened for
write. 

C<write()> will return 1.

=head1 AUTHOR

Dominique Dumont, (ddumont at cpan dot org)

=head1 SEE ALSO

L<Config::Model>, 
L<Config::Model::AutoRead>, 
L<Config::Model::Backend::Any>, 

=cut
