#!/usr/local/bin/perl -w
###########################################
# en-add - Add a note to Evernote
# Mike Schilli, 2012 (m@perlmeister.com)
###########################################
use strict;
use Thrift;
use Thrift::HttpClient;
use Thrift::BinaryProtocol;

use lib 'gen-perl';
use EDAMUserStore::Constants;
use EDAMUserStore::UserStore;
use EDAMNoteStore::NoteStore;
use EDAMErrors::Types;
use EDAMTypes::Types;

my $username        = "perlsnapshot";
my $password        = "*******";
my $consumer_key    = "perlsnapshot";
my $consumer_secret = "****************";

my( $message ) = @ARGV;
die "usage: $0 note" if !defined $message;

my $evernote_host = "evernote.com";
my $user_store_uri =
    "https://$evernote_host/edam/user";
my $note_store_uri_base =
    "https://$evernote_host/edam/note/";

my $http_client =
  Thrift::HttpClient->new($user_store_uri);
my $protocol = Thrift::BinaryProtocol->new(
  $http_client);

my $client =
  EDAMUserStore::UserStoreClient->new(
  $protocol);

my $version_ok =
  $client->checkVersion( "perlsnapshot",
EDAMUserStore::Constants::EDAM_VERSION_MAJOR,
EDAMUserStore::Constants::EDAM_VERSION_MINOR,
  );

if ( !$version_ok ) {
  die "Version not ok";
}

my $result =
  $client->authenticate( $username,
  $password, $consumer_key,
  $consumer_secret );

my $user = $result->user();

my $note_store_uri =
  $note_store_uri_base . $user->shardId();

my $note_store_client =
  Thrift::HttpClient->new($note_store_uri);

my $note_store_protocol =
  Thrift::BinaryProtocol->new(
    $note_store_client);

my $note_store =
  EDAMNoteStore::NoteStoreClient->new(
    $note_store_protocol);

my $notebooks =
  $note_store->listNotebooks(
    $result->authenticationToken() );

my $inbox_guid;

for my $notebook (@$notebooks) {
  if ( $notebook->name() eq "Inbox" ) {
    $inbox_guid = $notebook->guid();
    last;
  }
}

if ( !defined $inbox_guid ) {
  die "No Inbox notebook found";
}

my $note = EDAMTypes::Note->new();
$note->title( $message );
$note->content();

my $created =
  $note_store->createNote(
  $result->authenticationToken(), $note );

  # move new note to "Inbox"
$note_store->copyNote(
  $result->authenticationToken(),
  $created->guid(), $inbox_guid );
