package App::bif::new::identity;
use strict;
use warnings;
use Bif::Mo;
use Config::Tiny;
use DBIx::ThinSQL qw/bv/;
use IO::Prompt::Tiny qw/prompt/;
use Path::Tiny qw/path/;

our $VERSION = '0.1.5_3';
extends 'App::bif';

sub run {
    my $self   = shift;
    my $opts   = $self->opts;
    my $dbw    = $self->dbw;
    my $name   = '';
    my $email  = '';
    my $spacer = '';

    if ( $opts->{self} ) {
        print "Creating \"self\" identity:\n";

        my $git_conf_file = path( File::HomeDir->my_home, '.gitconfig' );
        my $git_conf = Config::Tiny->read($git_conf_file) || {};

        $name  = $git_conf->{user}->{name}  || 'Your Name';
        $email = $git_conf->{user}->{email} || 'your@email.adddr';

        $name =~ s/(^")|("$)//g;
        $email =~ s/(^")|("$)//g;

        $spacer = '  ';
    }

    $opts->{name} ||= prompt( $spacer . 'Name:', $name )
      || return $self->err( 'NameRequired', 'name is required' );

    my $short = join( '', $opts->{name} =~ m/(\b\w)/g );
    $opts->{shortname} ||= prompt( $spacer . 'Short Name:', $short )
      || return $self->err( 'NameRequired', 'shortname is required' );

    $opts->{method} ||= prompt( $spacer . 'Contact Method:', 'email' )
      || return $self->err( 'MethodRequired', 'method is required' );

    $opts->{value} ||=
      prompt( $spacer . 'Contact ' . ucfirst( $opts->{method} ) . ':', $email )
      || return $self->err( 'ValueRequired', 'value is required' );

    $opts->{message} ||= '';

    $dbw->txn(
        sub {
            $opts->{id}     = $dbw->nextval('topics');
            $opts->{ecm_id} = $dbw->nextval('topics');

            if ( $opts->{self} ) {
                $opts->{change_id} = $self->new_change(
                    author         => $opts->{name},
                    author_contact => bv( $opts->{value}, DBI::SQL_VARCHAR ),
                    author_contact_method => $opts->{method},
                    author_shortname      => $opts->{shortname},
                );
            }
            else {
                $opts->{change_id} = $self->new_change();
            }

            $dbw->xdo(
                insert_into => 'func_new_identity',
                values      => {
                    id        => $opts->{id},
                    change_id => $opts->{change_id},
                    name      => $opts->{name},
                    shortname => $opts->{shortname},
                    self      => $opts->{self},
                },
            );

            $dbw->xdo(
                insert_into => 'func_new_identity_contact_method',
                values      => {
                    change_id   => $opts->{change_id},
                    id          => $opts->{ecm_id},
                    identity_id => $opts->{id},
                    method      => $opts->{method},
                    mvalue      => bv( $opts->{value}, DBI::SQL_VARCHAR ),
                },
            );

            $dbw->xdo(
                insert_into => 'func_update_identity',
                values      => {
                    change_id                 => $opts->{change_id},
                    id                        => $opts->{id},
                    contact_id                => $opts->{id},
                    default_contact_method_id => $opts->{ecm_id},
                },
            );

            my $path = $dbw->xval(
                select => 'path',
                from   => 'topic_path tp',
                where  => { 'tp.id' => $opts->{id} },
            );

            $self->end_change(
                id            => $opts->{change_id},
                message       => $opts->{message},
                action_format => "new identity %s ($path), "
                  . "$opts->{name} ($opts->{shortname})",
                action_topic_id_1 => $opts->{id},
            );
        }
    );

    return $self->ok('NewIdentity');
}

1;
__END__

=head1 NAME

=for bif-doc #create

bif-new-identity - create a new identity in the repository

=head1 VERSION

0.1.5_3 (2015-06-30)

=head1 SYNOPSIS

    bif new identity [NAME] [METHOD] [VALUE] [OPTIONS...]

=head1 DESCRIPTION

The B<bif-new-identity> command creates a new object in the repository
representing an individual.

=head1 ARGUMENTS & OPTIONS

=over

=item NAME

The name of the identity.

=item METHOD

The default contact method type, typically "phone", "email", etc.

=item VALUE

The value of the default contact method, i.e. the phone number, the
email address, etc.

=item --message, -m MESSAGE

The creation message, set to "Created" by default.

=item --self

Register this identity as "myself" to be used for future changes.

=item --shortname, -s

The shortname (initials) to be shown in some outputs

=back

=head1 SEE ALSO

L<bif>(1)

=head1 AUTHOR

Mark Lawrence E<lt>nomad@null.netE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright 2013-2015 Mark Lawrence <nomad@null.net>

This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version.

