package CloudStore::JSON;
use warnings;
use strict;

use autodie;
use JSON::XS;
use File::Path qw();
use File::Slurp qw();

sub make_dir {
	my ( $dir, $json ) = @_;
	warn "### VFS make_dir $dir\n";
	File::Path::make_path($dir);
	$dir =~ s{/([^/]+)/?$}{/.$1};
	File::Slurp::write_file $dir, $json if $json;
}

sub remove_dir {
	warn "### VFS remove_dir $_[0]\n";
	File::Path::remove_tree(@_);
}

sub remove_file {
	warn "### VFS unlink $_[0]\n";
	unlink $_[0];
}

sub write_file {
	warn "### VFS ", -e $_[0] ? 'modify' : 'write', "_file $_[0]\n";
	File::Slurp::write_file(@_);
}

sub read_file {
	my $path = shift;
	warn "### VFS read_file $path\n";
	$path =~ s{/([^/]+)/?$}{/.$1} if -d $path;
	File::Slurp::read_file($path);
}

sub rsync_transfer {
	my ( $data ) = @_;
	my $json = encode_json $data;

	my $path = "users/$data->{login}/json/$data->{file}";

	if ( $data->{itemize} =~ m/^[c>]([fd])/ ) { # received change/create
		my $type = $1;

		if ( $type eq 'f' ) {
			if ( $path =~ m{^(.+)/[^/]+$} ) { # have dir
				make_dir $1, $json if ! -e $1;
			}
			write_file $path, $json;
		} elsif ( $type eq 'd' ) {
			make_dir $path, $json;
		} else {
			die "unknown type $type";
		}
	} elsif ( $data->{itemize} =~ m/\*deleting/ ) {
		if ( -d $path ) {
			remove_dir $path;
		} elsif ( -f $path ) {
			remove_file $path;
		} else {
			warn "ignored delete $path";
		}
	}
	return $json;
}

sub file_data {
	my $path = shift;
	$path =~ s{/blob/}{/json/};
	return decode_json read_file $path;
}

1;
