#!/usr/local/bin/perl -w
###########################################
# autokeygen - Generate an Autokey config
#   based on a .yaml spec
# Mike Schilli, 2015 (m@perlmeister.com)
###########################################
use strict;
use Sysadm::Install qw(:all);
use YAML qw( LoadFile );
use JSON qw( from_json to_json );

my $yaml_file   = "autokey.yaml";
my( $base_dir ) = 
  glob "~/.config/autokey/data";
my $script_dir  = 
  "$base_dir/Sample Scripts";
my $phrase_dir  = "$base_dir/My Phrases";

for my $entry (
    @{ LoadFile $yaml_file } ) {
  my $func = "process_$entry->{type}";
  no strict 'refs';
  $func->( $entry );
}

###########################################
sub process_script {
###########################################
  my( $entry ) = @_;

    # get template script
  my $data = 
    json_rw( "Insert Date", $script_dir );

  $data->{ hotkey } = hotkey( $entry );
  $data->{ description } = $entry->{ name };
  $data->{ modes } = [ 3 ];

  json_rw( $entry->{ name }, $script_dir, 
           $data );

  blurt( "system.exec_command(" .
      "'$entry->{exec}')\n", 
      "$script_dir/$entry->{ name }.py" );

}

###########################################
sub hotkey {
###########################################
  my( $entry ) = @_;

  my @mods = split /-/, $entry->{ hotkey };
  my $key = pop @mods;

  return { 
    hotKey    => $key,
    modifiers => [ map { "<$_>" } @mods ],
  };
}

###########################################
sub process_phrase {
###########################################
  my( $entry ) = @_;

    # get template phrase
  my $data = 
    json_rw( "Second phrase", $phrase_dir );

  $data->{ abbreviation }->
    { abbreviations }->[ 0 ] = 
      $entry->{ abbrv };

  $data->{ description } 
    = $entry->{ name };

  $data->{ modes } = [ 1 ];

  json_rw( $entry->{ name }, $phrase_dir,
           $data );

  blurt( "$entry->{ text }\n", 
    "$phrase_dir/$entry->{ name }.txt" );
}

###########################################
sub json_rw {
###########################################
  my( $name, $dir, $data ) = @_;

  my $path = "$dir/.$name.json";

  if( defined $data ) {
    return blurt to_json( 
          $data, { pretty => 1 } ), $path;
  }

  return from_json( slurp $path );
}
