package Cpanel::Easy::Utils::Print;

# cpanel10 - Cpanel/Easy/Utils/Print.pm   Copyright(c) 2005-2007 cPanel, Inc.
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cpanel license. Unauthorized copying is prohibited

use strict;
use warnings;
no warnings qw(redefine);

sub print_configure {
    my ( $self, $ns ) = @_;
    $ns = $self->headless_caller_ns() if !$ns;
    $self->{'ui_obj'}->alert_over_last_twiddle( $self, "\n\t\t./configure\n" . join( "\n", map { "\t\t\t$_" } $self->get_configure_as_array($ns) ) . "\n" );
}

sub print_alert {
    my ( $self, @maketext ) = @_;
    $self->debug();
    my $end = $maketext[0] =~ m{^\s*\n} ? '!!' : ' !!';
    my $string = '!! ' . $self->maketext(@maketext) . "$end\n";
    $self->print_to_log($string);

    if ( ( $self->{'_'}{'in-pretests'} || !$self->get_param('build') ) && ref $self->{'ui_obj'} eq 'Cpanel::Easy::Apache::UI::HTML' ) {
        eval 'use Cpanel::CPAN::Text::InHTML ();';
        $string = Cpanel::CPAN::Text::InHTML::encode_plain($string);
    }

    $self->print_to_screen($string);
}

sub print_alert_color {
    my ( $self, $color, @maketext ) = @_;
    my $end = $maketext[0] =~ m{^\s*\n} ? '!!' : ' !!';
    my $string = '!! ' . $self->maketext(@maketext) . "$end\n";
    $self->print_to_log($string);
    $self->{'ui_obj'}->print_to_screen_color( $self, $color, $string );
}

sub print_to_screen {
    my ( $self, $string ) = @_;
    return if !defined $string;

    $self->{'ui_obj'}->print_to_screen( $self, $string );
}

sub print_to_log {
    my ( $self, $string ) = @_;
    return if !defined $string;

    # reopen in append mode if fh is not open
    if ( !fileno $self->{'log_fh'} ) {
        open $self->{'log_fh'}, '>>', $self->{'log_file'};
        chmod 0600, $self->{'log_file'};

        # or log or die or ???
    }

    print { $self->{'log_fh'} } $string;
}

sub print_to_log_and_screen {
    my ( $self, $string ) = @_;
    return if !defined $string;
    chomp $string;
    $string .= "\n";
    $self->print_to_log($string);
    $self->print_to_screen($string);
}

sub print_verbose_aware {
    my ( $self, $string ) = @_;
    return if !defined $string;
    chomp $string;
    $string .= "\n";

    if ( $self->{'_'}{'prefs'}{'verbose'} || !$self->{'twiddler'} ) {
        $self->print_to_log_and_screen($string);
    }
    else {
        $self->print_to_log($string);
        $self->print_to_screen( $self->get_next_twiddler() );
    }
}

1;
