
package JK::Lib::iPhone;

use strict;
use File::Temp;
use JK::Lib::Misc;

my @EXPORT = qw/get_config sb_popup/;

sub get_contacts {
    my $value = shift;

    my $sql = <<__EOS__
  SELECT p.rowid, p.first, p.last, p.organization, p.imageuri, m.property, m.value
    FROM abperson p, abmultivalue m
   WHERE p.rowid = m.record_id
     AND m.property IN (3,4)
     AND m.value
__EOS__
    ;
    if( $value ){
        if( $value =~ /^(\d{3})(\d{3})(\d{4})$/ ){
            my($npa,$nxx,$snum) = ($1,$2,$3);
            # because we ask for 2155551212
            # and the db may have 2155551212 or (215) 555-1212 or ...
            $sql .= " LIKE '%${npa}%${nxx}%${snum}'";
        }else{
            $sql .= ' = ' . $::dbh{a}->quote($value);
        }
    }else{
        $sql .= ' NOT NULL';
    }

    my %tmp;
    my $sth = $::dbh{a}->prepare($sql);
    $sth->execute;
    while(my $row=$sth->fetchrow_hashref){

        if( $row->{property} == 3 ){
            # dont manipulate an email addr
            $row->{value} =~ s/[^\d]//g; # 1 (215) 555-1212 -> 12155551212
            $row->{value} =~ s/^1//;     # we want 10 digits, not 11
        }
    
        my $n;
        if( $row->{First} ){
            $row->{First} =~ s/[^a-zA-Z\s]//g;
            $n = $row->{First};
            if( $row->{Last} ){
                $row->{Last} =~ s/[^a-zA-Z\s]//g;
                $n .= " $row->{Last}";
            }
        }elsif( $row->{Organization} ){
            $row->{Organization} =~ s/[^a-zA-Z\s]//g;
            $n = $row->{Organization};
        }
        if( $n ){
            $tmp{ $row->{value} } = { name  => $n,
                                      image => $row->{ImageURI},
                                    };
            debug( "saved contacts{ $row->{value} }" );
        }
    }

    if( $value ){
        return( $tmp{$value} );
    }else{
        $tmp{TIME} = time();
        return( \%tmp );
    }
}

sub get_mynum {
    my $pl = '/var/wireless/Library/Preferences/com.apple.commcenter.plist';

    debug( "* reading commcenter config" );
    open( my $plutil, "plutil -key PhoneNumber $pl 2>&1 |" ) || slowerr( "cannot fork plutil: $!" );
    chomp(my $line=<$plutil>);
    close $plutil;

    my ($n) = $line =~ /(\d{10})$/;

    return $n;
}

sub get_myaddr {
    my $pl = '/var/wireless/Library/Preferences/com.apple.accountsettings.plist';

    debug( "* reading accountsettings config" );
    open( my $plutil, "plutil -key Accounts -key ChildAccounts -key Username $pl 2>&1 |" ) || slowerr( "cannot fork plutil: $!" );
    chomp(my $line=<$plutil>);
    close $plutil;

    return $line;
}

sub get_mac {
    my $int = shift || slowerr( "get_mac: specify interface" );

    debug( "* getting mac for int: $int" );
    open( my $icfg, '-|', 'ifconfig', $int ) || slowerr( "cannot fork ifconfig: $!" );
    while(<$icfg>){
        next unless( /ether/ );
        my $mac = (split, /\s+/)[1];
        return $mac;
    }
    close $icfg;
}

sub get_config {
    my $plist = shift || slowerr( "get_config: specify plist" );

    debug( "* reading PreferenceLoader config" );

    my %ncfg;
    open( PLIST, "plutil $plist 2>&1 |" ) || slowerr( "cannot fork plutil: $!" );
    while(<PLIST>){
        next unless( /^\s*"?([^"]+)"?\s+=\s+"?([^"]+)"?;/ );
        my ($key,$value) = ($1,$2);
        if( $key eq 'minutes_alert' || $key eq 'data_alert' ){
            my $plan = $key;
            $plan =~ s/_alert$//;
            for my $alert (split /\s+/, $value){
                my($type,$thresholds) = split(/:/, $alert);
                unless( $type eq 'dynamic' || $type eq 'static' ){
                    sb_popup('Warning',
                             "$key is broken in iWarden Settings! ($type)",
                             'Dismiss');
                    next;
                }
                for my $threshold (split /,/, $thresholds){
                    if( int($threshold) eq $threshold ){
                        push @{$ncfg{$key}{$type}}, $threshold;
                        debug( "* push \@{ncfg{$key}{$type}}, $threshold" );
                    }else{
                        sb_popup('Warning',
                                 "$key is broken in iWarden Settings! ($threshold)",
                                 'Dismiss');
                    }
                }
            }
        }else{
            $ncfg{$key} = $value;
            debug( "* ncfg{$key} = $value" );
        }
    }
    close PLIST;
    return( \%ncfg );
}

sub sb_popup {
    my $title = shift;
    my $msg = shift;
    my $button = shift;

    # this is too lame XXX QQQ
    my $fh = File::Temp->new();
    my $fname = $fh->filename;
    print $fh <<__EOF__
#!/usr/bin/cycript -p SpringBoard

var message = [[UIAlertView alloc] init];
message.title = "$title";
message.message = "$msg";
[message addButtonWithTitle:\@"$button"];

[message show];
__EOF__
    ;

    close $fh;
    chmod(0744, $fname);
    system( $fname );
}

sub import {
    my $pkg = shift;
    my $caller = caller;

    for my $f ( @EXPORT ){
        no strict;
        *{$caller . '::' . $f} = $pkg->can($f);
    }
}

1;
