#!/usr/bin/env node

// Core modules
var fs = require('fs');
var path = require('path');

// Generate the root folder of snippets
var snippetsRoot = path.join(process.env.HOME, '.snips');

// Logging
var chalk = require('chalk');
var error = function (statement) { chalk.bold.red('[FAIL] ' + statement); };

// For creating the application
var program = require('commander');

program
    .version(JSON.parse(fs.readFileSync('package.json')).version);

// Create a code-snippet
program
    .command('create [snippet-name]')
    .description('Create a code snippet with given name')
    .action(function (snippetName) {
        // Generate fileName
        var fileName = path.join(snippetsRoot, snippetName);

        // Check if there exists a snippet with the given name
        if (fs.existsSync(fileName)) {
            error('Snippet Exists');
            process.exit(1);
        }

        // Open up vim for creating the snippet and then wait for close
        var editor = require('child_process').spawn(process.env.EDITOR, [fileName], {stdio: 'inherit'});
        editor.on('exit', process.exit);
    });

// List all snippets
program
    .command('list')
    .description('List all snippets')
    .action(function() {
        fs.readdir(snippetsRoot, function (err, items) {
            if (err) {
                error('Filesystem error');
                process.exit(1);
            }

            // List all the snippets
            items.forEach(function(item) {
                console.log(item);
            });
        });
    });

// Parse arguments
program.parse(process.argv);

@@ -832,17 +832,25 @@
 Snippet 
-E
+already e
 xists');
@@ -1528,24 +1528,24 @@
         %7D);%0A
-
         %7D);%0A
@@ -1553,16 +1553,831 @@
    %7D);%0A%0A
+// Copy a snippet to the clipboard%0Aprogram%0A    .command('copy %5Bsnippet-name%5D')%0A    .description('Copy snippet to clipboard if it exists')%0A    .action(function (snippetName) %7B%0A        // Generate fileName%0A        var fileName = path.join(snippetsRoot, snippetName);%0A%0A        // Check if there exists a snippet with the given name%0A        if (!fs.existsSync(fileName)) %7B%0A            process.exit(0);%0A        %7D%0A%0A        // Get the text from the file%0A        var text = fs.readFileSync(fileName).toString();%0A%0A        // Copy the text to clipboard%0A        require('copy-paste').copy(text, function() %7B process.exit(0); %7D);%0A    %7D);%0A%0A// Search for a string in all snippets%0Aprogram%0A    .command('search %3Csearch-terms%3E')%0A    .description('Search snippets for given search term')%0A    .action(function(searchTerm) %7B%0A%0A    %7D);%0A%0A
 // Parse

copy to clipboard; search is wip