<commit_before>TempSettings = new Meteor.Collection null
Template.admin.onCreated ->
	if not RocketChat.settings.cachedCollectionPrivate?
		RocketChat.settings.cachedCollectionPrivate = new RocketChat.CachedCollection({ name: 'private-settings', eventType: 'onAll' })
		RocketChat.settings.collectionPrivate = RocketChat.settings.cachedCollectionPrivate.collection
		RocketChat.settings.cachedCollectionPrivate.init()

	RocketChat.settings.collectionPrivate.find().observe
		added: (data) ->
			TempSettings.insert data
		changed: (data) ->
			TempSettings.update data._id, data
		removed: (data) ->
			TempSettings.remove data._id

Template.admin.onDestroyed ->
	TempSettings.remove {}

Template.admin.helpers
	languages: ->
		languages = TAPi18n.getLanguages()
		result = []
		for key, language of languages
			result.push _.extend(language, { key: key })
		result = _.sortBy(result, 'key')
		result.unshift {
			"name": "Default",
			"en": "Default",
			"key": ""
		}
		return result;

	appLanguage: (key) ->
		if !key
			return !RocketChat.settings.get('Language')
		selected = (RocketChat.settings.get('Language'))?.split('-').shift().toLowerCase() is key
		return selected

	group: ->
		group = FlowRouter.getParam('group')
		group ?= TempSettings.findOne({ type: 'group' })?._id
		return TempSettings.findOne { _id: group, type: 'group' }

	sections: ->
		group = FlowRouter.getParam('group')
		group ?= TempSettings.findOne({ type: 'group' })?._id
		settings = TempSettings.find({ group: group }, {sort: {section: 1, sorter: 1, i18nLabel: 1}}).fetch()

		sections = {}
		for setting in settings
			if setting.i18nDefaultQuery?
				if _.isString(setting.i18nDefaultQuery)
					i18nDefaultQuery = JSON.parse(setting.i18nDefaultQuery)
				else
					i18nDefaultQuery = setting.i18nDefaultQuery

				if not _.isArray(i18nDefaultQuery)
					i18nDefaultQuery = [i18nDefaultQuery]

				found = 0
				for item in i18nDefaultQuery
					if TempSettings.findOne(item)?
						setting.value = TAPi18n.__(setting._id + '_Default')

			sections[setting.section or ''] ?= []
			sections[setting.section or ''].push setting

		sectionsArray = []
		for key, value of sections
			sectionsArray.push
				section: key
				settings: value

		return sectionsArray

	i18nDefaultValue: ->
		return TAPi18n.__(@_id + '_Default')

	isDisabled: ->
		if @blocked
			return { disabled: 'disabled' }

		if not @enableQuery?
			return {}

		if _.isString(@enableQuery)
			enableQuery = JSON.parse(@enableQuery)
		else
			enableQuery = @enableQuery

		if not _.isArray(enableQuery)
			enableQuery = [enableQuery]

		found = 0
		for item in enableQuery
			if TempSettings.findOne(item)?
				found++

		return if found is enableQuery.length then {} else {disabled: 'disabled'}

	isReadonly: ->
		if @readonly is true
			return { readonly: 'readonly' }

	hasChanges: (section) ->
		group = FlowRouter.getParam('group')

		query =
			group: group
			changed: true

		if section?
			if section is ''
				query.$or = [
					{section: ''}
					{section: {$exists: false}}
				]
			else
				query.section = section

		return TempSettings.find(query).count() > 0

	translateSection: (section) ->
		if section.indexOf(':') > -1
			return section

		return t(section)

	flexOpened: ->
		return 'opened' if RocketChat.TabBar.isFlexOpen()

	arrowPosition: ->
		console.log 'room.helpers arrowPosition' if window.rocketDebug
		return 'left' unless RocketChat.TabBar.isFlexOpen()

	label: ->
		label = @i18nLabel or @_id
		return TAPi18n.__ label if label

	description: ->
		description = TAPi18n.__ @i18nDescription if @i18nDescription
		if description? and description isnt @i18nDescription
			return description

	sectionIsCustomOAuth: (section) ->
		return /^Custom OAuth:\s.+/.test section

	callbackURL: (section) ->
		id = s.strRight(section, 'Custom OAuth: ').toLowerCase()
		return Meteor.absoluteUrl('_oauth/' + id)

	relativeUrl: (url) ->
		return Meteor.absoluteUrl(url)

	selectedOption: (_id, val) ->
		return RocketChat.settings.collectionPrivate.findOne({_id: _id})?.value is val

	random: ->
		return Random.id()

	getEditorOptions: (readOnly = false) ->
		return {} =
			lineNumbers: true
			mode: this.code or "javascript"
			gutters: [
				"CodeMirror-linenumbers"
				"CodeMirror-foldgutter"
			]
			foldGutter: true
			matchBrackets: true
			autoCloseBrackets: true
			matchTags: true,
			showTrailingSpace: true
			highlightSelectionMatches: true
			readOnly: readOnly

	setEditorOnBlur: (_id) ->
		Meteor.defer ->
			codeMirror = $('.code-mirror-box[data-editor-id="'+_id+'"] .CodeMirror')[0].CodeMirror
			if codeMirror.changeAdded is true
				return

			onChange = ->
				value = codeMirror.getValue()
				TempSettings.update {_id: _id},
					$set:
						value: value
						changed: RocketChat.settings.collectionPrivate.findOne(_id).value isnt value

			onChangeDelayed = _.debounce onChange, 500

			codeMirror.on 'change', onChangeDelayed
			codeMirror.changeAdded = true

		return
<commit_msg>Fix error CodeMirror undefined when leaving admin<commit_after>TempSettings = new Meteor.Collection null
Template.admin.onCreated ->
	if not RocketChat.settings.cachedCollectionPrivate?
		RocketChat.settings.cachedCollectionPrivate = new RocketChat.CachedCollection({ name: 'private-settings', eventType: 'onAll' })
		RocketChat.settings.collectionPrivate = RocketChat.settings.cachedCollectionPrivate.collection
		RocketChat.settings.cachedCollectionPrivate.init()

	RocketChat.settings.collectionPrivate.find().observe
		added: (data) ->
			TempSettings.insert data
		changed: (data) ->
			TempSettings.update data._id, data
		removed: (data) ->
			TempSettings.remove data._id

Template.admin.onDestroyed ->
	TempSettings.remove {}

Template.admin.helpers
	languages: ->
		languages = TAPi18n.getLanguages()
		result = []
		for key, language of languages
			result.push _.extend(language, { key: key })
		result = _.sortBy(result, 'key')
		result.unshift {
			"name": "Default",
			"en": "Default",
			"key": ""
		}
		return result;

	appLanguage: (key) ->
		if !key
			return !RocketChat.settings.get('Language')
		selected = (RocketChat.settings.get('Language'))?.split('-').shift().toLowerCase() is key
		return selected

	group: ->
		group = FlowRouter.getParam('group')
		group ?= TempSettings.findOne({ type: 'group' })?._id
		return TempSettings.findOne { _id: group, type: 'group' }

	sections: ->
		group = FlowRouter.getParam('group')
		group ?= TempSettings.findOne({ type: 'group' })?._id
		settings = TempSettings.find({ group: group }, {sort: {section: 1, sorter: 1, i18nLabel: 1}}).fetch()

		sections = {}
		for setting in settings
			if setting.i18nDefaultQuery?
				if _.isString(setting.i18nDefaultQuery)
					i18nDefaultQuery = JSON.parse(setting.i18nDefaultQuery)
				else
					i18nDefaultQuery = setting.i18nDefaultQuery

				if not _.isArray(i18nDefaultQuery)
					i18nDefaultQuery = [i18nDefaultQuery]

				found = 0
				for item in i18nDefaultQuery
					if TempSettings.findOne(item)?
						setting.value = TAPi18n.__(setting._id + '_Default')

			sections[setting.section or ''] ?= []
			sections[setting.section or ''].push setting

		sectionsArray = []
		for key, value of sections
			sectionsArray.push
				section: key
				settings: value

		return sectionsArray

	i18nDefaultValue: ->
		return TAPi18n.__(@_id + '_Default')

	isDisabled: ->
		if @blocked
			return { disabled: 'disabled' }

		if not @enableQuery?
			return {}

		if _.isString(@enableQuery)
			enableQuery = JSON.parse(@enableQuery)
		else
			enableQuery = @enableQuery

		if not _.isArray(enableQuery)
			enableQuery = [enableQuery]

		found = 0
		for item in enableQuery
			if TempSettings.findOne(item)?
				found++

		return if found is enableQuery.length then {} else {disabled: 'disabled'}

	isReadonly: ->
		if @readonly is true
			return { readonly: 'readonly' }

	hasChanges: (section) ->
		group = FlowRouter.getParam('group')

		query =
			group: group
			changed: true

		if section?
			if section is ''
				query.$or = [
					{section: ''}
					{section: {$exists: false}}
				]
			else
				query.section = section

		return TempSettings.find(query).count() > 0

	translateSection: (section) ->
		if section.indexOf(':') > -1
			return section

		return t(section)

	flexOpened: ->
		return 'opened' if RocketChat.TabBar.isFlexOpen()

	arrowPosition: ->
		console.log 'room.helpers arrowPosition' if window.rocketDebug
		return 'left' unless RocketChat.TabBar.isFlexOpen()

	label: ->
		label = @i18nLabel or @_id
		return TAPi18n.__ label if label

	description: ->
		description = TAPi18n.__ @i18nDescription if @i18nDescription
		if description? and description isnt @i18nDescription
			return description

	sectionIsCustomOAuth: (section) ->
		return /^Custom OAuth:\s.+/.test section

	callbackURL: (section) ->
		id = s.strRight(section, 'Custom OAuth: ').toLowerCase()
		return Meteor.absoluteUrl('_oauth/' + id)

	relativeUrl: (url) ->
		return Meteor.absoluteUrl(url)

	selectedOption: (_id, val) ->
		return RocketChat.settings.collectionPrivate.findOne({_id: _id})?.value is val

	random: ->
		return Random.id()

	getEditorOptions: (readOnly = false) ->
		return {} =
			lineNumbers: true
			mode: this.code or "javascript"
			gutters: [
				"CodeMirror-linenumbers"
				"CodeMirror-foldgutter"
			]
			foldGutter: true
			matchBrackets: true
			autoCloseBrackets: true
			matchTags: true,
			showTrailingSpace: true
			highlightSelectionMatches: true
			readOnly: readOnly

	setEditorOnBlur: (_id) ->
		Meteor.defer ->
			return if not $('.code-mirror-box[data-editor-id="'+_id+'"] .CodeMirror')[0]

			codeMirror = $('.code-mirror-box[data-editor-id="'+_id+'"] .CodeMirror')[0].CodeMirror
			if codeMirror.changeAdded is true
				return

			onChange = ->
				value = codeMirror.getValue()
				TempSettings.update {_id: _id},
					$set:
						value: value
						changed: RocketChat.settings.collectionPrivate.findOne(_id).value isnt value

			onChangeDelayed = _.debounce onChange, 500

			codeMirror.on 'change', onChangeDelayed
			codeMirror.changeAdded = true

		return

{'fraction_non_alphanumeric': 0.12278091837746702, 'fraction_numerical': 0.010611921055241495, 'mean_word_length': 3.770104068117313, 'pattern_counts': {'":': 6, '<': 3, '<?xml version=': 0, '>': 61, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4931675', 'n_tokens_mistral': 3837, 'n_tokens_neox': 3199, 'n_words': 751}