#!/usr/bin/env perl
#
# Get your Opera Link speeddials and bookmarks
#
# Usage:
#   ./link-api-example

use strict;
use warnings;

use lib '../lib';

use Data::Dumper;
use JSON::XS ();
use Net::OperaLink ();
use File::Slurp ();

# Test keys. Get your own at:
#   https://auth.opera.com/service/oauth/applications/

our $CONSUMER_KEY    = 'test_desktop_key';
our $CONSUMER_SECRET = 'p2FlOFGr3XFm5gOwEKKDcg3CvA4pp0BC';

my $rc_file = exists $ENV{HOME}
    ? "$ENV{HOME}/.operalinkrc"
    : ".operalinkrc" ;

# Read tokens from the .rc file
sub restore_tokens {
    my @tokens;

    if (-s $rc_file) {
        @tokens = File::Slurp::read_file($rc_file);
        chomp @tokens;
        if (
            (@tokens != 2) ||
            ($tokens[0] !~ m{^ [\w\-]+ $}x) ||
            ($tokens[1] !~ m{^ [\w\-]+ $}x)
        ) {
            die "Invalid tokens in $rc_file. Maybe delete '$rc_file?'\n";
        }
    }

    return @tokens;
}

# Save tokens to the .rc file
sub save_tokens {
    my (@tokens) = @_;

    open(my $rc_fh, ">$rc_file")
        or die "Can't open $rc_file: $!";
    print $rc_fh $tokens[0], "\n", $tokens[1], "\n";
    close $rc_fh;
}

my $link = Net::OperaLink->new(
    consumer_key    => $CONSUMER_KEY,
    consumer_secret => $CONSUMER_SECRET,
);

# You'll save the token and secret in cookie, config file or session database
my ($access_token, $access_token_secret) = restore_tokens();
if ($access_token && $access_token_secret) {
    $link->access_token($access_token);
    $link->access_token_secret($access_token_secret);
}

unless ($link->authorized) {
    # The client is not yet authorized: Do it now
    print
        "Please authorize me at ", $link->get_authorization_url, " and then\n",
        "type the verifier + ENTER to continue\n";
    chomp (my $verifier = <STDIN>);
    my($access_token, $access_token_secret) = $link->request_access_token(verifier => $verifier);
    save_tokens($access_token, $access_token_secret);
}

my $notes = $link->notes();

for my $note (@{$notes}) {

    my $id = $note->{id};
    my $content = $note->{properties}->{content};
    my @content = split /\r?\n/, $content;
    my $title = $note->{properties}->{url} || $content[0];

    printf "* %s (%s)\n", $title, $id;

    for (@content) {
        print "\t\t", $_, "\n";
    }

    print "\n";
}

my $res = $link->speeddial(1);
if (not defined $res) {
    print 'Error: ', $link->error(), "\n";
}
else {
    print Dumper($res), "\n";
}

$res = $link->bookmarks();
if (not defined $res) {
    print 'Error: ', $link->error(), "\n";
}
else {
    print Dumper($res), "\n";
}

$res = $link->bookmark("C2C69E604EE811DF8536E0FA4A1F0025");
if (not defined $res) {
    print 'Error: ', $link->error(), "\n";
}
else {
    print Dumper($res), "\n";
}

