'use babel';

var fuzzy = require('fuzzy');
var _ = require('lodash');
var fManager = require('./function-manager');
var fileManager = require('./file-manager');

export default class PgProvider {
  constructor(basePath) {
    self = this;
    this.selector = '.source.sql, source.pgsql';
    this.disableForSelector = '.source.sql .comment';
    this.excludeLowerPriority = true;
    this.inclusionPriority = 1;
    this.storeData = {};
    this.lastPrefix = "";
    this.activatedManuallyCount = 0;
    fManager.loadFunctions(basePath);
  }

  getSuggestions({editor, bufferPosition, scopeDescriptor, prefix, activatedManually}) {
    if (prefix.length < 2){
        return;
    }
    var checkFunctions = false;
    if (this.lastPrefix == prefix) {
      checkFunctions = this.activatedManuallyCount % 2 === 0;
      this.activatedManuallyCount++;
    } else {
      this.activatedManuallyCount = 0;
      this.lastPrefix = prefix;
      checkFunctions = activatedManually;
    }
    var checkVariables = prefix.length > 1;
    var checkTokens = prefix.length > 3;

    //Must get the prev word and evaluate if it is (FROM or .)
    self = this;
    let allSuggestions = new Array();
    var match = undefined;

    var fileContent = atom.workspace.getActiveTextEditor().getText();
    if (fileContent !== null) {
      fileManager.loadCurrentFile(fileContent);
    }
    // Variables
    if (checkVariables) {
      var variables = fileManager.getVariables();
      var result = _.keys(variables);
      var results = fuzzy.filter(prefix, result);
      var matches = results.map(function(el) {
        return el.string;
      });
      _.forEach(matches, function (value) {
        var variable = variables[value];
        var variableType = variable.type;
        var argmode = variable.argmode;
        var suggestionType = variable.isParam ? "property" : "variable";
        allSuggestions.push({"text":value, "type": suggestionType, "leftLabel":variableType, "rightLabel": argmode});
      });
    }

    // Tokens
    if (checkTokens) {
      var tokens = fileManager.getTokens();
      var results = fuzzy.filter(prefix, tokens);
      var matches = results.map(function(el) {
        return el.string;
      });
      _.forEach(matches, function (value) {
        if (prefix != value) {
          allSuggestions.push({"text":value});
        }
      });
    }

    // Functions
    if (checkFunctions) {
      var functions = fManager.getFunctions();
      var result = _.keys(functions);
      var results = fuzzy.filter(prefix, result);
      var matches = results.map(function(el) {
        return el.string;
      });
      _.forEach(matches, function (value) {
        match = functions[value][0];
        var snippet = PgProvider.createSnippet(value, match.params.in);
        allSuggestions.push({"text":value, "type":"function", "leftLabel":match.returnType, "snippet":snippet});
      });
    }


    return allSuggestions;
  }

  static createSnippet(functionName, inParams) {
    var snippet = functionName + "(";
    var index = 1;
    _.map(inParams, (param) => {
      snippet += "${"+(index++)+":"+param.name+" "+param.type+"}, ";
    });
    snippet = snippet.trim().replace(/\,$/, '');
    snippet += ")${"+(index++)+"}";
    return snippet;
  }


}

@@ -490,24 +490,68 @@
 yCount = 0;%0A
+    this.functionsSuggestionActive = false;%0A
     fManager
@@ -799,64 +799,96 @@
     
-checkFunctions = this.activatedManuallyCount %25 2 === 0;%0A
+if (activatedManually !== undefined) %7B%0A        this.functionsSuggestionActive = true;%0A  
     
@@ -920,16 +920,24 @@
 ount++;%0A
+      %7D%0A
     %7D el
@@ -941,16 +941,118 @@
  else %7B%0A
+      if (prefix.indexOf(this.lastPrefix) === -1) %7B%0A        this.functionsSuggestionActive = false;%0A  
       th
@@ -1078,24 +1078,32 @@
 yCount = 0;%0A
+      %7D%0A
       this.l
@@ -1120,24 +1120,29 @@
 = prefix;%0A  
+  %7D%0A%0A
     checkFun
@@ -1150,16 +1150,55 @@
 tions = 
+this.functionsSuggestionActive && this.
 activate
@@ -1206,23 +1206,32 @@
 Manually
-;%0A    %7D
+Count %25 2 !== 0;
 %0A    var
@@ -3190,16 +3190,130 @@
 s;%0A  %7D%0A%0A
+  onDidInsertSuggestion(%7Beditor, triggerPosition, suggestion%7D) %7B%0A    this.functionsSuggestionActive = false;%0A  %7D%0A%0A
   static

Fix to suggest functions