#---------------------------------------------------------------
# ____                   _ _         ____  _
#|  _ \ ___  _   _  __ _| | |_ _   _/ ___|| |__   __ _ _ __ ___
#| |_) / _ \| | | |/ _` | | __| | | \___ \| '_ \ / _` | '__/ _ \
#|  _ < (_) | |_| | (_| | | |_| |_| |___) | | | | (_| | | |  __/
#|_| \_\___/ \__, |\__,_|_|\__|\__, |____/|_| |_|\__,_|_|  \___|
#            |___/             |___/
#
# Copyright (C) 2011 RoyaltyShare, Inc.   All Rights Reserved
#---------------------------------------------------------------
package BookPub::RDAS::Process::SaveCredential;

use lib '/app/tools/common/lib';
use Common::Assert;

use lib '/app/tools/bookpub/lib';
use BookPub::ServiceCredential;

use base 'Common::Script';

sub _options {
    {
        client_id => {
            short       => 'c',
            required    => 1,
            description => 'Client ID',
            parameter   => 'i'
        },
        service_id => {
            short       => 's',
            required    => 1,
            description => 'Service ID',
            parameter   => 'i'
        },
        username => {
            short       => 'u',
            required    => 1,
            description => 'Username',
            parameter   => 's'
        },
        password => {
            short       => 'p',
            description => 'Password',
            parameter   => 's'
        },
        show => {
            description => 'Display credentials for user'
        },
    };
}

sub _process {
    my $self = shift;

    if ( $self->param('show') ) {
        $self->_showCredentials();
    } else {
        $self->_setCredentials();
    }
}

sub _showCredentials {
    my $self = shift;

    my $credential = new BookPub::ServiceCredential( serviceID => $self->param('service_id') );

    if ($credential) {
        $credential->print();
    } else {
        print "No credentials found\n";
    }
}

sub _setCredentials {
    my $self      = shift;
    my $serviceID = $self->param('service_id');
    my $username  = $self->param('username');
    my $password  = $self->param('password');

    assert($serviceID);
    assert($username);

    $self->error("password required.") unless ($password);

    my $credential = new BookPub::ServiceCredential( serviceID => $self->param('service_id') )
      || new BookPub::ServiceCredential();

    $credential->ServiceID($serviceID);
    $credential->Username($username);
    $credential->Password($password);

    $credential->save();
}

1;
