#!/usr/bin/perl
use strict;
use warnings;
use FindBin;
use lib "$FindBin::Bin/../lib";
use Bookmarks;
use Bookmarks::Utils;
use YAML;

my $links;
{
    my $yaml;
    local $/;
    $yaml = <>;
    $links=YAML::Load($yaml);
}

my %fields=(
    description => 'title',
    extended => 'descr',
    created => 'add_date',
    modified => 'last_access_date',
);

Bookmarks::M::DB::Links->db_Main()->{sqlite_handle_binary_nulls} = 1;
Bookmarks::M::DB::Links->autoupdate(0);

for my $link (@$links) {
    print "Loading $link->{href}\n";
    my $dblink=Bookmarks::M::DB::Links->find_or_create({
        url => $link->{href},
    });
    if (!Bookmarks::Utils::check_link($link->{href})) {
        warn "Link $link->{href} non valido, marco come tale\n";
        $link->{description}.=' [INVALID]';
    }
    else {
        $dblink->set_icon(Bookmarks::Utils::get_site_icon($link->{href}));
    }
    $link->{created}||=time();
    $link->{modified}||=time();
    while (my ($f1,$f2) = each %fields) {
        $dblink->$f2($link->{$f1});
    }
    $dblink->update();

    Bookmarks::M::DB::LinksTags->search({link => $dblink->pk()})->delete_all();

    for my $tagname (@{$link->{tags}}) {
        my $dbtag=Bookmarks::M::DB::Tags->find_or_create({
            name => $tagname,
        });

        Bookmarks::M::DB::LinksTags->find_or_create({
            tag => $dbtag->pk(),
            link => $dblink->pk(),
        });
    }
}
