#!/usr/local/bin/perl -w
use strict;

BEGIN {
    use FindBin qw($Bin);
    chdir $Bin;
}

use local::lib;
use Thrift;
use Thrift::HttpClient;
use Thrift::BinaryProtocol;

use lib 'gen-perl';
use EDAMUserStore::Constants;
use EDAMUserStore::UserStore;
use EDAMNoteStore::NoteStore;
use EDAMNoteStore::Types;
use EDAMErrors::Types;
use EDAMTypes::Types;
use DateTime;
use Log::Log4perl qw(:easy);

my( $home ) = glob "~";

Log::Log4perl->easy_init( {
    level => $DEBUG, category => "main",
    file =>
   ">>$home/data/evernote-tickler.log" } );

my $username        = "my-user";
my $password        = "my-passwd";
my $consumer_key    = "perlsnapshot";
my $consumer_secret = "my-consumer-secret";

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 $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 $tickler_guid;
my $inbox_guid;

for my $notebook (@$notebooks) {
  if ( $notebook->name() eq "01-Tickler" ){
    $tickler_guid = $notebook->guid();
    DEBUG "Found Tickler notebook";
  }
  if ( $notebook->name() eq "00-Inbox" ) {
    $inbox_guid = $notebook->guid();
    DEBUG "Found Inbox notebook";
  }
}

if ( !defined $tickler_guid ) {
  die "No Tickler notebook found";
}

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

my $filter =
    EDAMNoteStore::NoteFilter->new();
$filter->notebookGuid( $tickler_guid );

my $note_list = $note_store->findNotes(
    $result->authenticationToken(),
        $filter, 0, 1000 );

my $tomorrow = DateTime->today(
time_zone => "local" )->add( days => 1 );
my $tomorrow_date_match = $tomorrow->ymd();

for my $note (
    @{ $note_list->{ notes } } ) {
  my $title = $note->title();

  my( $date_in_title ) =
      ( $title =~ /^(\S+)/ );

  DEBUG "Check if $tomorrow_date_match ",
        "matches '$date_in_title'";

  if( $tomorrow_date_match =~
      /^$date_in_title/ ) {

    DEBUG "$title matches. Move to Inbox.";

    my $worked = $note_store->copyNote(
        $result->authenticationToken(),
        $note->guid(), $inbox_guid );

    die "copy note failed ($!)" if
      !defined $worked;

    DEBUG "Deleting note in Tickler file";

    $note_store->deleteNote(
        $result->authenticationToken(),
        $note->guid() );
    }
}