package XXV::MODULES::CHANNELS;

use strict;

use Tools;
use Event::File;
use Locale::gettext;
use File::stat;

# This module method must exist for XXV
# ------------------
sub module {
# ------------------
    my $obj = shift || return error ('No Object!' );
    my $args = {
        Name => 'CHANNELS',
        Description => gettext('This module want read new Channels Data and save this in the Database.'),
        Version => '0.45',
        Date => '11.09.2005',
        Author => 'xpix',
        Status => sub{ $obj->status(@_) },
        Preferences => {
            file => {
                description => gettext('Location of channels.conf on your system.'),
                default     => '/var/lib/vdr/channels.conf',
                type        => 'file',
                required    => gettext('This is required!'),
            },
            interval => {
                description => gettext('The interval to parse channels to DB in sec'),
                default     => 300,
                type        => 'integer',
                required    => gettext('This is required!'),
            },
            empty => {
                description => gettext('Include channels with empty PID'),
                default     => 'n',
                type        => 'confirm',
            },
            filterCA => {
                description => gettext('Filter channels, set all wanted CA(Common Access)'),
                # 0 for FTA, 1-4 for DVB Device, 32001 for AnalogPlugin
                type        => 'list',
                options     => 'multi',
                default     => '',
                choices     => sub{
                    my @knownCA;
                    foreach my $CA (@{$obj->{knownCA}}) {
                        my $desc;
                        if($CA eq '0')              { $desc = gettext("Free to air"); }
                        elsif($CA >= 1 && $CA <= 4) { $desc = sprintf(gettext("DVB card %s"),$CA);}
                        else                        { $desc = sprintf("CA '%s'",$CA);      }
                        push(@knownCA,[$desc,$CA]);
                    }
                    return @knownCA;
                },
                check   => sub{
                    my $value = shift;
                    if(ref $value eq 'ARRAY') {
                        return join(',', @$value);
                    } else {
                        return $value;
                    }
                },
            },
            stripCH => {
                description => gettext("Clean channel names, only the 'long' part is visible."),
    			# Format in vdr 1.2.6 (Format "" or "long"). it show also all parts
    			# Format in vdr 1.3.10 (Format "short,long")
    			# Format in vdr 1.3.12 (Format "short,long;provider")
    			# Format in vdr 1.3.?? (Format "provider;short,long")
    			# Format in vdr 1.3.18 (Format "short,long;provider")
                default     => 'short,long;provider',
                type        => 'string',
            },
        },
        Commands => {
            cstatus => {
                description => gettext('Status from Channels Data'),
                short       => 'ct',
                callback    => sub{ $obj->status(@_) },
            },
            cupdate => {
                description => gettext('Read Channels and write into Database'),
                short       => 'cu',
                callback    => sub{ $obj->readData(@_) },
            },
            clist => {
                description => gettext("List Channels from database 'cname'"),
                short       => 'cl',
                callback    => sub{ $obj->list(@_) },
            },
            cnew => {
                description => gettext("Create a new channel"),
                short       => 'cne',
                callback    => sub{ $obj->newChannel(@_) },
                Level       => 'user',
                DenyClass   => 'cedit',
            },
            cedit => {
                description => gettext("Edit a channel 'cid'"),
                short       => 'ced',
                callback    => sub{ $obj->editChannel(@_) },
                Level       => 'user',
                DenyClass   => 'cedit',
            },
            cdelete => {
                description => gettext("Delete one or more channels 'pos'"),
                short       => 'cdl',
                callback    => sub{ $obj->deleteChannel(@_) },
                Level       => 'user',
                DenyClass   => 'cedit',
            },
        },
    };
    return $args;
}

# ------------------
sub status {
# ------------------
    my $obj = shift || return error ('No Object!' );
    my $watcher = shift;
    my $console = shift;
    my $lastReportTime = shift || 0;

    my $sql = "select count(*) from CHANNELS";
    my $gesamt = $obj->{dbh}->selectall_arrayref($sql)->[0][0];

    $sql = "select count(*) from CHANNELGROUPS";
    my $groups = $obj->{dbh}->selectall_arrayref($sql)->[0][0];

    return {
        message => sprintf(gettext('The system has %d saved Channels in %d Groups'), $gesamt, $groups),
    };

}

# ------------------
sub new {
# ------------------
	my($class, %attr) = @_;
	my $self = {};
	bless($self, $class);

    # paths
    $self->{paths} = delete $attr{'-paths'};

	# who am I
    $self->{MOD} = $self->module;

    # all configvalues to $self without parents (important for ConfigModule)
    map {
        $self->{$_} = $attr{'-config'}->{$self->{MOD}->{Name}}->{$_} || $self->{MOD}->{Preferences}->{$_}->{default}
    } keys %{$self->{MOD}->{Preferences}};

    # read the DB Handle
    $self->{dbh} = delete $attr{'-dbh'};

    $self->{knownCA} = [0,1,2,3,4];

    # The Initprocess
    my $erg = $self->init or return error('Problem to initialze Module');

    # Interval to read channels and put to DB
    Event->timer(
        interval => $self->{interval},
        prio => 6,  # -1 very hard ... 6 very low
        cb => sub{
            lg 'Start the interval reading channels to DB!';
            $self->readData();
        },
    );

	return $self;
}

# ------------------
sub init {
# ------------------
    my $obj = shift || return error ('No Object!' );

    # Old Version
    if(tableExists($obj->{dbh}, 'CHANNELS')) {
        $obj->{dbh}->do('drop table CHANNELS')
             unless(grep(/CA/,@{fields($obj->{dbh}, 'select * from CHANNELS')}));
        $obj->{dbh}->do('drop table CHANNELS')
             unless(grep(/GROUP/,@{fields($obj->{dbh}, 'select * from CHANNELS')}));
    }

    # Look for table or create this table
    my $version = main::getVersion;
    $obj->{dbh}->do(qq|
      CREATE TABLE IF NOT EXISTS CHANNELS (
          Id varchar(100) NOT NULL,
          Name varchar(100) NOT NULL default '',
          Frequency int(11) NOT NULL default '0',
          Parameters varchar(100) default '',
          Source varchar(100),
          Srate varchar(100) default '',
          VPID varchar(100) default '',
          APID varchar(100) default '',
          TPID varchar(100) default '',
          CA varchar(100) default '',
          SID varchar(100) default '',
          NID varchar(100) default '',
          TID varchar(100) default '',
          RID varchar(100) default '',
          GRP int(11) default 0,
          POS int(11) NOT NULL,
          PRIMARY KEY  (Id)
        ) COMMENT = '$version'
    |);

    $obj->{dbh}->do(qq|
      CREATE TABLE IF NOT EXISTS CHANNELGROUPS (
          Id int(11) auto_increment not NULL,
          Name varchar(100) default 'unknown',
          Counter int(11) default '0',
          PRIMARY KEY  (Id)
        ) COMMENT = '$version'
    |);

    main::after(sub{
        $obj->{svdrp} = main::getModule('SVDRP');
        my $erg = $obj->readData();
    }, "CHANNELS: Read and register Channels ...", 5);
    return 1;
}

# ------------------
sub insert {
# ------------------
    my $obj = shift || return error ('No Object!' );
    my $data = shift || return;
    my $pos = shift || return;
    my $grp = shift || 0;

    foreach my $CA (split(',', $data->[8])) {
        push(@{$obj->{knownCA}},$CA);
    }

    return if($obj->{empty} eq 'n' and not (($data->[6] ne "0" || $data->[7] ne "0"))); # Ignore Channels with APID = 0/TPID = 0 from PID Scan
    if($obj->{filterCA}) {
       my $filter = $obj->{filterCA};
       $filter =~ s/\,/|/g; # Transform 0,2,400 => 0|2|400
       return 0 if(not ($data->[8] =~ /(^|\,)($filter)(\,|$)/s)); # check (^|,)(0|2|400)(,|$)
    }

	# Strip short and providername from channelname e.g ch
    if($obj->{stripCH}) {
		my $ch = $data->[0];
		my $filter = $obj->{stripCH};
		my @p = split(';',$filter);
		if(scalar @p == 2) {
			if(($p[0] =~ /provider/i)) { # format "provider;name"
				$ch = (split(';', $ch))[-1] if($ch =~ /;/);
				$filter = $p[1];
			}
			elsif(($p[1] =~ /provider/i)) { # format "name;provider"
				$ch = (split(';', $ch))[0] if($ch =~ /;/);
				$filter = $p[0];
			}
		}
		my @c = split(',',$filter);
		if(scalar @c == 2) {
			if(($c[0] =~ /long/i)) { # format "long,short"
				$ch = (split(',', $ch))[0] if($ch =~ /,/);
			}
			elsif(($c[1] =~ /long/i)) { # format "short,long"
				$ch = (split(',', $ch))[-1] if($ch =~ /,/);
			}
		}
	    $data->[0] = $ch if($ch);
	}

    # ID
    if ( $data->[3] eq 'C' or $data->[3] eq 'T') {
	    $data->[1]=substr($data->[1], 0, 3);
    }

    my $id;
    $data->[12] = (split(':', $data->[12]))[0];
#   if($data->[12] && $data->[12] > 0 && $data->[12] < 100) {
    # By DVB-C gabs Probleme weil die Zahl grösser 100 war
    # Siehe auch http://www.vdr-portal.de/board/thread.php?sid=&postid=364373
    if($data->[12] && $data->[12] > 0) {
        $id = sprintf('%s-%u-%u-%u-%u', $data->[3], $data->[10], ($data->[10] || $data->[11]) ? $data->[11] : $data->[1], $data->[9],$data->[12]);
    } else {
        $id = sprintf('%s-%u-%u-%u', $data->[3], $data->[10], ($data->[10] || $data->[11]) ? $data->[11] : $data->[1], $data->[9]);
    }
    unshift(@$data, $id);

    # ChannelGroup
    push(@$data, $grp);

    # POS
    push(@$data, $pos);

    my $sth = $obj->{dbh}->prepare('REPLACE INTO CHANNELS VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)');
    $sth->execute( @$data );
    lg sprintf('Add new Channel "%s" with Id "%s" in ChannelsDB!', $data->[1], $id);
    return 1;
}

# ------------------
sub insertGrp {
# ------------------
    my $obj = shift || return error ('No Object!' );
    my $pos = shift || return;
    my $name = shift || 0;

    my $sql = sprintf('INSERT INTO CHANNELGROUPS SET Name=%s, Counter=%d', $obj->{dbh}->quote($name), $pos);
    lg sprintf('Add new ChannelGroup "%s" in ChannelsGroup!', $name);
    if($obj->{dbh}->do($sql)) {
        return $obj->{dbh}->{mysql_insertid};
    }
}

# ------------------
sub readData {
# ------------------
    my $obj = shift || return error ('No Object!' );
    my $watcher = shift;
    my $console = shift;
    my $file = $obj->{file} || return 1, warn ('No Channels File');

    return 1, warn ('No Channels File found') if( ! -e $file);

    # only if file modification from last read time
    my $mtime = (stat($file)->mtime);
    return
      if(! ref $console and defined $obj->{LastRefreshTime} and ($mtime > $obj->{LastRefreshTime}));

    $obj->{dbh}->do('DELETE FROM CHANNELS');
    $obj->{dbh}->do('DELETE FROM CHANNELGROUPS');

    my $fh = IO::File->new("< $file") or return error("Can't open File $file $! ");
    my $c = 0;
    my $nPos = 1;
    my $grp = 0;
    while ( defined (my $line = <$fh>) ) {
        $line =~ s/[\r|\n]//sig;
        next if($line eq "");
        my @data = split(':', $line, 13);
        $data[-1] = (split(':', $data[-1]))[0];

        if( $line =~ /^\:\@(\d*)\s*(.*)/ and $nPos < $1) {
            $nPos = $1;
            my $grpText = $2;
            $grp = $obj->insertGrp($nPos, $grpText);
        } elsif( $line =~ /^\:(.+)/) {
            my $grpText = $1;
            $grp = $obj->insertGrp($nPos, $grpText);
        } else {
            $grp = $obj->insertGrp(1, gettext("Channels"))
                if(!$grp);
            $c++
                if(scalar @data > 4 && $obj->insert(\@data, $nPos++, $grp));
        }
    }
    $fh->close;

    $console->message(sprintf(gettext("Write %d Channels in Database."), $c))
        if(ref $console);

    # sort list with CA numerical
    my %CA;
    @CA{@{$obj->{knownCA}}} = ();
    @{$obj->{knownCA}} = sort { if(is_numeric($a) && is_numeric($b)) {
                                    $a <=> $b
                                } else {
                                    $a cmp $b } } keys %CA;

    $obj->{LastRefreshTime} = $mtime;
    return 1;
}
# ------------------
sub getnum {
# ------------------
    use POSIX qw(strtod);
    my $str = shift;
    $str =~ s/^\s+//;
    $str =~ s/\s+$//;
    $! = 0;
    my($num, $unparsed) = strtod($str);
    if (($str eq '') || ($unparsed != 0) || $!) {
        return undef;
    } else {
        return $num;
    }
}
# ------------------
sub is_numeric { defined getnum($_[0]) }
# ------------------

# ------------------
sub list {
# ------------------
    my $obj = shift || return error ('No Object!' );
    my $watcher = shift || return error ('No Watcher!');
    my $console = shift || return error ('No Console');
    my $id      = shift || '';
    my $params = shift;

    my $sql = qq|
select
    c.*, cg.Name as __GrpName
from
    CHANNELS as c,
    CHANNELGROUPS as cg
where
    c.Name like '%$id%'
    and
    c.GRP = cg.Id
|;

    my $fields = fields($obj->{dbh}, $sql);

    my $sortby = "POS";
    $sortby = $params->{sortby}
        if(exists $params->{sortby} && grep(/^$params->{sortby}$/i,@{$fields}));
    $sql .= "order by $sortby";
    $sql .= " desc"
        if(exists $params->{desc} && $params->{desc} == 1);



    my $erg = $obj->{dbh}->selectall_arrayref($sql);
    unshift(@$erg, $fields);
    $console->table($erg,{sortable => 1 });
}


# ------------------
sub NameToChannel {
# ------------------
    my $obj = shift || return error ('No Object!' );
    my $name = shift || return undef;

    my $sql = sprintf('select Id from CHANNELS where UPPER(Name) = UPPER("%s")', $name);
    my $erg = $obj->{dbh}->selectall_arrayref($sql);
    return $erg->[0][0];
}

# ------------------
sub PosToName {
# ------------------
    my $obj = shift || return error ('No Object!' );
    my $pos = shift || return undef;

    my $sql = sprintf('select Name from CHANNELS where POS = "%lu"', $pos);
    my $erg = $obj->{dbh}->selectall_arrayref($sql);
    return $erg->[0][0];
}

# ------------------
sub PosToChannel {
# ------------------
    my $obj = shift || return error ('No Object!' );
    my $pos = shift || return undef;

    my $sql = sprintf('select Id from CHANNELS where POS = "%lu"', $pos);
    my $erg = $obj->{dbh}->selectall_arrayref($sql);
    return $erg->[0][0];
}

# ------------------
sub ChannelGroupsArray {
# ------------------
    my $obj = shift || return error ('No Object!' );
    my $field = shift || return undef;

    my $sql = sprintf('select %s, Id from CHANNELGROUPS order by Id', $field);
    my $erg = $obj->{dbh}->selectall_arrayref($sql);
    return $erg;
}

# ------------------
sub ChannelArray {
# ------------------
    my $obj = shift || return error ('No Object!' );
    my $field = shift || return undef;

    my $sql = sprintf('select %s, POS from CHANNELS order by POS', $field);
    my $erg = $obj->{dbh}->selectall_arrayref($sql);
    return $erg;
}

# ------------------
sub ChannelHash {
# ------------------
    my $obj = shift || return error ('No Object!' );
    my $field = shift || return undef;

    my $sql = sprintf('select * from CHANNELS');
    my $erg = $obj->{dbh}->selectall_hashref($sql, $field);
    return $erg;
}

# ------------------
sub ChannelToName {
# ------------------
    my $obj = shift || return error ('No Object!' );
    my $id = shift || return undef;
    my $sql = sprintf('select Name from CHANNELS where Id = "%s"', $id);
    my $erg = $obj->{dbh}->selectall_arrayref($sql);
    return $erg->[0][0];
}

# ------------------
sub ChannelToPos {
# ------------------
    my $obj = shift || return error ('No Object!' );
    my $id = shift || return undef;
    my $sql = sprintf('select POS from CHANNELS where Id = "%s"', $id);
    my $erg = $obj->{dbh}->selectall_arrayref($sql);
    return $erg->[0][0];
}

# ------------------
sub newChannel {
# ------------------
    my $self         = shift || return error ('No Object!' );
    my $watcher      = shift || return error ('No Watcher!');
    my $console      = shift || return error ('No Console');
    my $id           = shift || 0;
    my $defaultData  = shift || 0;

    $self->editChannel($watcher, $console, 0, $defaultData);
}

# ------------------
sub editChannel {
# ------------------
    my $self    = shift || return error ('No Object!' );
    my $watcher = shift || return error ('No Watcher!');
    my $console = shift || return error ('No Console');
    my $cid     = shift || 0;  # If channelid then edit channel
    my $data    = shift || 0;  # Data for defaults

    my $defaultData;
    if($cid and not ref $data) {

        $cid = $self->PosToChannel($cid)
            if(int($cid) > 0);

        $defaultData = $self->{dbh}->selectrow_hashref("select POS, Name, Frequency, Parameters, Source, Srate, VPID, APID, TPID, CA, SID, NID, TID, RID from CHANNELS where Id = '$cid'")
            or return $console->message(sprintf(gettext("Channel '%s' is not exist in database!"),$cid));
    } elsif (ref $data eq 'HASH') {
        $defaultData = $data;
    }

    my $questions = [
        'POS' => {
            typ     => 'hidden',
            def     => $defaultData->{POS} || 0,
        } ];

    my $newpos = [
        'NEWPOS' => {
            typ     => 'integer',
            msg     => gettext('Position'),
            def     => int($defaultData->{POS}),
            check   => sub{
                my $value = shift;
                if(int($value) > 0) {
                    return int($value);
                } else {
                    return undef, gettext('No right Value!');
                }
            },
        } ];
    #Change Position only on editing
    push(@{$questions},@{$newpos})
        if($cid && main::getVdrVersion >= 10332);

    my $more = [
        'Name' => {
            typ     => 'string',
            def     => $defaultData->{Name} || gettext('New channel'),
            msg     => gettext("Name"),
            check   => sub{
                my $value = shift || return;
                if($value ne '') {
                    return $value;
                } else {
                    return undef, gettext('This is required!');
                }
            },
        },
        'Frequency' => {
            typ     => 'integer',
            msg     => gettext('Transponder frequency'),
            def     => int($defaultData->{Frequency}) || 0,
            check   => sub{
                my $value = shift;
                if(int($value) > 0) {
                    return int($value);
                } else {
                    return undef, gettext('No right Value!');
                }
            },
        },
        'Source' => {
            typ     => 'string',
            def     => $defaultData->{Source} || "",
            msg     => gettext("Signal source"),
            check   => sub{
                my $value = shift || return;
                if($value ne '') {
                    return $value;
                } else {
                    return undef, gettext('This is required!');
                }
            },
        },
        'Parameters' => {
            typ     => 'string',
            def     => $defaultData->{Parameters} || "",
            msg     => gettext("Various parameters, depends on signal source"),
            check   => sub{
                my $value = shift || return;
                if($value ne '') {
                    return $value;
                } else {
                    return undef, gettext('This is required!');
                }
            },
        },
        'Srate' => {
            typ     => 'integer',
            msg     => gettext('Symbol rate'),
            def     => int($defaultData->{Srate}) || 27500,
            check   => sub{
                my $value = shift;
                if(int($value) > 0) {
                    return int($value);
                } else {
                    return undef, gettext('No right Value!');
                }
            },
        },
        'VPID' => {
            typ     => 'integer',
            msg     => gettext('Video PID (VPID)'),
            def     => int($defaultData->{VPID}) || 0,
            check   => sub{
                my $value = shift;
                if(int($value) >= 0) {
                    return int($value);
                } else {
                    return undef, gettext('No right Value!');
                }
            },
        },
        'APID' => {
            typ     => 'string',
            def     => $defaultData->{APID} || 0,
            msg     => gettext("Audio PID (APID)"),
            check   => sub{
                my $value = shift || return;
                if($value ne '') {
                    return $value;
                } else {
                    return undef, gettext('This is required!');
                }
            },
        },
        'TPID' => {
            typ     => 'integer',
            msg     => gettext('Teletext PID (TPID)'),
            def     => int($defaultData->{TPID}) || 0,
            check   => sub{
                my $value = shift;
                if(int($value) >= 0) {
                    return int($value);
                } else {
                    return undef, gettext('No right Value!');
                }
            },
        },
        'CA' => {
            typ     => 'string',
            def     => $defaultData->{CA} || 0,
            msg     => gettext("Conditional access (CA)"),
            check   => sub{
                my $value = shift || return;
                if($value ne '') {
                    return $value;
                } else {
                    return undef, gettext('This is required!');
                }
            },
        },
        'SID' => {
            typ     => 'integer',
            msg     => gettext('Service ID (SID)'),
            def     => int($defaultData->{SID}) || 0,
            check   => sub{
                my $value = shift;
                if(int($value) >= 0) {
                    return int($value);
                } else {
                    return undef, gettext('No right Value!');
                }
            },
        },
        'NID' => {
            typ     => 'integer',
            msg     => gettext('Network ID (NID)'),
            def     => int($defaultData->{NID})  || 0,
            check   => sub{
                my $value = shift;
                if(int($value) >= 0) {
                    return int($value);
                } else {
                    return undef, gettext('No right Value!');
                }
            },
        },
        'TID' => {
            typ     => 'integer',
            msg     => gettext('Transport stream ID (TID)'),
            def     => int($defaultData->{TID})  || 0,
            check   => sub{
                my $value = shift;
                if(int($value) >= 0) {
                    return int($value);
                } else {
                    return undef, gettext('No right Value!');
                }
            },
        },
        'RID' => {
            typ     => 'integer',
            msg     => gettext('Radio ID (RID)'),
            def     => int($defaultData->{RID})  || 0,
            check   => sub{
                my $value = shift;
                if(int($value) >= 0) {
                    return int($value);
                } else {
                    return undef, gettext('No right Value!');
                }
            },
        },
    ];
    push(@{$questions},@{$more});

    # Ask Questions
    my $datasave = $console->question(($cid ? gettext('Edit channel')
                                            : gettext('New channel')), $questions, $data);

    if(ref $datasave eq 'HASH') {
        my $erg = $self->saveChannel($datasave, $datasave->{POS});

        $console->message($erg);
        lg sprintf('%s channel with name "%s" is saved from User: %s',
            ($cid ? 'New' : 'Changed'),
            $data->{Name},
            $console->{USER}->{Name}
            );

        sleep(1);
        $self->readData($watcher,$console);

        $console->redirect({url => $console->{browser}->{Referer}, wait => 2})
            if($console->typ eq 'HTML');
    }
}

# ------------------
sub saveChannel {
# ------------------
    my $self = shift || return error ('No Object!' );
    my $data = shift || return error('No Data to Save!');
    my $pos = shift || 0;

    my $erg;

    if($pos
       && defined $data->{NEWPOS}
       && $pos != $data->{NEWPOS} ) {
       $erg = $self->{svdrp}->command(
            sprintf("movc %s %s",
            $pos,
            $data->{NEWPOS}
       ));
       $pos = $data->{NEWPOS};
       push(@{$erg},"\r\n");
   }

    $erg = $self->{svdrp}->command(
        sprintf("%s %s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s:%s",
            $pos ? "modc $pos" : "newc",
            $data->{Name},
            int($data->{Frequency}),
            $data->{Parameters},
            $data->{Source},
            int($data->{Srate}),
            int($data->{VPID}),
            $data->{APID},
            int($data->{TPID}),
            $data->{CA} ? $data->{CA} : '0',
            int($data->{SID}),
            int($data->{NID}),
            int($data->{TID}),
            int($data->{RID})
        )
    );
    return $erg;
}

# ------------------
sub deleteChannel {
# ------------------
    my $self = shift || return error ('No Object!' );
    my $watcher = shift;
    my $console = shift;
    my $channelid = shift || return $console->err(gettext("No channel to delete! Please use cdelete 'pos'"));
    my $answer  = shift || 0;

    my @channels  = reverse sort{ $a <=> $b } split(/[^0-9]/, $channelid);

    my $sql = sprintf("select * from CHANNELS where POS in (%s)", join(',', @channels));
    my $data = $self->{dbh}->selectall_hashref($sql, 'POS');

    foreach my $pos (@channels) {
        unless(exists $data->{$pos}) {
            $console->err(sprintf(gettext("Channel with number '%s' is not exist in database!"), $pos));
            next;
        }

        if(ref $console and $console->{TYP} ne 'HTML') {
            $console->table($data->{$pos});
            my $confirm = $console->confirm({
                typ   => 'confirm',
                def   => 'y',
                msg   => gettext('Are you sure to delete this channel?'),
            }, $answer);
            next if(! $answer eq 'y');
        }

        lg sprintf('Channel with name "%s" is deleted from User: %s',
            $data->{$pos}->{Name},
            $console->{USER}->{Name}
            );

        $self->{svdrp}->queue_cmds("delc $pos"); # Sammeln der Kommandos
    }

    if($self->{svdrp}->queue_cmds('COUNT')) {
        my $erg = $self->{svdrp}->queue_cmds("CALL"); # Aufrufen der Kommandos
        $console->msg($erg, $self->{svdrp}->err)
            if(ref $console);

        sleep(1);

        $self->readData($watcher,$console);

        $console->redirect({url => $console->{browser}->{Referer}, wait => 1})
            if(ref $console and $console->typ eq 'HTML');
    } else {
        $console->err(gettext("No channel to delete!"));
    }

    return 1;
}

1;
