"use strict";

var _ = require("underscore");
// A wrapper around twitter's typeahead library with some sane defaults

require('typeahead');

var $ = require("jquery"),
    mustache = require("mustache"),
    Bacon = require("baconjs"),
    keyCodeIs = require("./baconUtils").keyCodeIs;

function setTypeahead($typeahead, val) {
    $typeahead.typeahead('setQuery', val);
}

function setTypeaheadAfterDataLoaded($typeahead, key, query) {
    if (!key) {
        setTypeahead($typeahead, query);
    } else if (query && query.length !== 0) {
        var data = _.filter(
            $typeahead.data('ttView').datasets[0].itemHash,
            function(data) {
                return data.datum[key] == query;
            });

        if (data.length > 0) {
            setTypeahead($typeahead, data[0].value);
        }
    } else {
        setTypeahead($typeahead, '');
    }
}

exports.create = function(options) {
    var config = options.config,
        template = mustache.compile($(options.template).html()),
        $input = $(options.input),
        $hidden_input = $(options.hidden),
        reverse = options.reverse;

    $input.typeahead({
        name: options.name, // Used for caching
        prefetch: {
            url: options.url,
            ttl: 0 // TODO: Use high TTL and invalidate cache on change
        },
        limit: 10,
        template: template
    });

    if (options.hidden) {
        var selectStream = $input.asEventStream('typeahead:selected typeahead:autocompleted',
                                                function(e, datum) { return datum; })
                                 .map(".id"),

            backspaceOrDeleteStream = $input.asEventStream('keyup')
                                            .filter(keyCodeIs([8, 46]))
                                            .map("");

        selectStream.merge(backspaceOrDeleteStream)
                    .onValue($hidden_input, "val");


        // Specify a 'reverse' key to lookup data in reverse,
        // otherwise restore verbatim
        $input.asEventStream('typeahead:initialized')
            .onValue(function () {
                var value = $hidden_input.val();
                if (value) {
                    setTypeaheadAfterDataLoaded($input, reverse, value);
                }
            });



        $hidden_input.on('restore', function(event, value) {
            // If we're already loaded, this applies right away
            setTypeaheadAfterDataLoaded($input, reverse, value);

            // If we're not, this will get used when loaded later
            $hidden_input.val(value || '');
        });

    }
};

@@ -873,16 +873,99 @@
    %7D%0A%7D%0A%0A
+exports.getDatum = function($typeahead) %7B%0A    return $typeahead.data('datum');%0A%7D;%0A%0A
 exports.
@@ -1468,38 +1468,8 @@
 );%0A%0A
-    if (options.hidden) %7B%0A    
     
@@ -1590,36 +1590,32 @@
                 
-    
 function(e, datu
@@ -1639,60 +1639,11 @@
 ; %7D)
-%0A                                 .map(%22.id%22),%0A%0A    
+,%0A%0A
     
@@ -1742,20 +1742,16 @@
         
-    
 .filter(
@@ -1769,16 +1769,18 @@
 8, 46%5D))
+,%0A
 %0A       
@@ -1784,127 +1784,292 @@
     
-                                    .map(%22%22);%0A%0A        selectStream.merge(backspaceOrDeleteStream)%0A                    
+editStream = selectStream.merge(backspaceOrDeleteStream.map(undefined)),%0A%0A        idStream = selectStream.map(%22.id%22)%0A                                .merge(backspaceOrDeleteStream.map(%22%22));%0A%0A%0A    editStream.onValue($input, %22data%22, %22datum%22);%0A%0A    if (options.hidden) %7B%0A        idStream
 .onV

Save current typeahead datum, add function for retrieving it