<commit_before>kd                              = require 'kd'
globals                         = require 'globals'
remote                          = require('app/remote').getInstance()

_                               = require 'lodash'
hljs                            = require 'highlight.js'
Encoder                         = require 'htmlencode'
dateFormat                      = require 'dateformat'

FSHelper                        = require 'app/util/fs/fshelper'
showError                       = require 'app/util/showError'
applyMarkdown                   = require 'app/util/applyMarkdown'

CustomViews                     = require 'app/commonviews/customviews'
IDEEditorPane                   = require 'ide/workspace/panes/ideeditorpane'
CredentialListItem              = require './credentiallistitem'
ComputeController_UI            = require 'app/providers/computecontroller.ui'
AccountCredentialList           = require 'account/accountcredentiallist'
AccountCredentialListController = require 'account/views/accountcredentiallistcontroller'

StackTemplateList               = require './stacktemplatelist'
StackTemplateListController     = require './stacktemplatelistcontroller'


module.exports = class StacksCustomViews extends CustomViews

  # This will be used if stack template is not defined yet
  DEFAULT_TEMPLATE = """
  {
    "provider": {
      "aws": {
        "access_key": "${var.access_key}",
        "secret_key": "${var.secret_key}",
        "region": "eu-central-1"
      }
    },
    "resource": {
      "aws_instance": {
        "example": {
          "instance_type": "t2.micro",
          "ami": "ami-936d9d93"
        }
      }
    }
  }
  """

  parseTerraformOutput = (response) ->

    # An example of a valid stack template
    # ------------------------------------
    # title: "Default stack",
    # description: "Koding's default stack template for new users",
    # machines: [
    #   {
    #     "label" : "koding-vm-0",
    #     "provider" : "koding",
    #     "instanceType" : "t2.micro",
    #     "provisioners" : [
    #         "devrim/koding-base"
    #     ],
    #     "region" : "us-east-1",
    #     "source_ami" : "ami-a6926dce"
    #   }
    # ],

    out = machines: []

    {machines} = response

    for machine, index in machines

      {label, provider, region} = machine
      {instance_type, ami} = machine.attributes

      out.machines.push {
        label, provider, region
        source_ami   : ami
        instanceType : instance_type
        provisioners : [] # TODO what are we going to do with provisioners? ~ GG
      }

    console.info "[parseTerraformOutput]", out.machines

    return out.machines


  handleCheckTemplate = (options, callback) ->

    { stackTemplate } = options
    { computeController } = kd.singletons

    computeController.getKloud()
      .checkTemplate { stackTemplateId: stackTemplate._id }
      .nodeify callback


  updateStackTemplate = (data, callback) ->

    { template, credential, title, stackTemplate, machines } = data

    title     or= 'Default stack template'
    credentials = [credential.publicKey]  if credential

    if stackTemplate
      dataToUpdate = if machines \
        then {machines} else {title, template, credentials}
      stackTemplate.update dataToUpdate, (err) ->
        callback err, stackTemplate
    else
      remote.api.JStackTemplate.create {
        title, template, credentials
      }, callback


  setGroupTemplate = (stackTemplate, callback) ->

    { groupsController } = kd.singletons

    currentGroup = groupsController.getCurrentGroup()
    { slug }     = currentGroup

    if slug is 'koding'
      message = 'Setting stack template for koding is disabled'
      new kd.NotificationView title: message
      return callback {message}

    currentGroup.modify stackTemplates: [ stackTemplate._id ], (err) ->
      return callback err  if err

      new kd.NotificationView
        title: "Group (#{slug}) stack has been saved!"

      callback()


  fetchAndShowCredentialData = (credential, outputView) ->

    outputView.addContent 'Fetching latest data...'

    credential.fetchData (err, data) ->
      if err
        outputView.addContent 'Failed: ', err.message
      else

        # Hide sensitive information
        provider = globals.config.providers[credential.provider]
        (Object.keys provider.credentialFields).forEach (field) ->
          data.meta[field] = '******************'

        try<commit_msg>StacksCustomViews: fetchAndShowCredentialData: no need to shadow these anymore<commit_after>kd                              = require 'kd'
globals                         = require 'globals'
remote                          = require('app/remote').getInstance()

_                               = require 'lodash'
hljs                            = require 'highlight.js'
Encoder                         = require 'htmlencode'
dateFormat                      = require 'dateformat'

FSHelper                        = require 'app/util/fs/fshelper'
showError                       = require 'app/util/showError'
applyMarkdown                   = require 'app/util/applyMarkdown'

CustomViews                     = require 'app/commonviews/customviews'
IDEEditorPane                   = require 'ide/workspace/panes/ideeditorpane'
CredentialListItem              = require './credentiallistitem'
ComputeController_UI            = require 'app/providers/computecontroller.ui'
AccountCredentialList           = require 'account/accountcredentiallist'
AccountCredentialListController = require 'account/views/accountcredentiallistcontroller'

StackTemplateList               = require './stacktemplatelist'
StackTemplateListController     = require './stacktemplatelistcontroller'


module.exports = class StacksCustomViews extends CustomViews

  # This will be used if stack template is not defined yet
  DEFAULT_TEMPLATE = """
  {
    "provider": {
      "aws": {
        "access_key": "${var.access_key}",
        "secret_key": "${var.secret_key}",
        "region": "eu-central-1"
      }
    },
    "resource": {
      "aws_instance": {
        "example": {
          "instance_type": "t2.micro",
          "ami": "ami-936d9d93"
        }
      }
    }
  }
  """

  parseTerraformOutput = (response) ->

    # An example of a valid stack template
    # ------------------------------------
    # title: "Default stack",
    # description: "Koding's default stack template for new users",
    # machines: [
    #   {
    #     "label" : "koding-vm-0",
    #     "provider" : "koding",
    #     "instanceType" : "t2.micro",
    #     "provisioners" : [
    #         "devrim/koding-base"
    #     ],
    #     "region" : "us-east-1",
    #     "source_ami" : "ami-a6926dce"
    #   }
    # ],

    out = machines: []

    {machines} = response

    for machine, index in machines

      {label, provider, region} = machine
      {instance_type, ami} = machine.attributes

      out.machines.push {
        label, provider, region
        source_ami   : ami
        instanceType : instance_type
        provisioners : [] # TODO what are we going to do with provisioners? ~ GG
      }

    console.info "[parseTerraformOutput]", out.machines

    return out.machines


  handleCheckTemplate = (options, callback) ->

    { stackTemplate } = options
    { computeController } = kd.singletons

    computeController.getKloud()
      .checkTemplate { stackTemplateId: stackTemplate._id }
      .nodeify callback


  updateStackTemplate = (data, callback) ->

    { template, credential, title, stackTemplate, machines } = data

    title     or= 'Default stack template'
    credentials = [credential.publicKey]  if credential

    if stackTemplate
      dataToUpdate = if machines \
        then {machines} else {title, template, credentials}
      stackTemplate.update dataToUpdate, (err) ->
        callback err, stackTemplate
    else
      remote.api.JStackTemplate.create {
        title, template, credentials
      }, callback


  setGroupTemplate = (stackTemplate, callback) ->

    { groupsController } = kd.singletons

    currentGroup = groupsController.getCurrentGroup()
    { slug }     = currentGroup

    if slug is 'koding'
      message = 'Setting stack template for koding is disabled'
      new kd.NotificationView title: message
      return callback {message}

    currentGroup.modify stackTemplates: [ stackTemplate._id ], (err) ->
      return callback err  if err

      new kd.NotificationView
        title: "Group (#{slug}) stack has been saved!"

      callback()


  fetchAndShowCredentialData = (credential, outputView) ->

    outputView.addContent 'Fetching latest data...'

    credential.fetchData (err, data) ->
      if err
        outputView.addContent 'Failed: ', err.message
      else

        try
{'fraction_non_alphanumeric': 0.1091074061472156, 'fraction_numerical': 0.003402517863218782, 'mean_word_length': 2.114800423878488, 'pattern_counts': {'":': 20, '<': 3, '<?xml version=': 0, '>': 20, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5212965', 'n_tokens_mistral': 2469, 'n_tokens_neox': 2350, 'n_words': 565}