<commit_before>/*global module:false*/
module.exports = function(grunt) {
  grunt.loadNpmTasks('grunt-contrib-yuidoc');
  grunt.loadNpmTasks('grunt-jasmine-task');
  grunt.loadNpmTasks('grunt-coffee');
  grunt.loadNpmTasks('grunt-css');
  grunt.loadNpmTasks('grunt-sizediff');
  grunt.loadNpmTasks('grunt-shell');

  // Project configuration.
  grunt.initConfig({
    dirs: {
      coffeeDir: 'coffeescripts',
      jsDir: 'bin/javascripts',
      cssDir: 'bin/css',
      testDir: 'tests'
    },
    pkg: '<json:nanoscroller.jquery.json>',
    meta: {
      unmin: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %>\n' +
        '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +
        '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
        ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */',
      min: '/*! <%= pkg.title || pkg.name %> v<%= pkg.version %> ' +
        '(c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
        ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
    },
    concat: {
      unmin: {
        src: ['<banner:meta.unmin>', '<file_strip_banner:bin/javascripts/<%= pkg.name %>.js>'],
        dest: '<%= dirs.jsDir %>/<%= pkg.name %>.js'
      },
      min: {
        src: ['<banner:meta.min>', '<file_strip_banner:bin/javascripts/<%= pkg.name %>.min.js>'],
        dest: '<%= dirs.jsDir %>/<%= pkg.name %>.min.js'
      }
    },
    csslint: {
      all: {
        src: '<%= dirs.cssDir %>/nanoscroller.css',
        rules: {
            'fallback-colors': false,
            'known-properties': false,
            'compatible-vendor-prefixes': false,
            'adjoining-classes': false,
            'empty-rules': true,
            'zero-units': true,
            ids: true,
            important: true
        }
      }
    },
    coffee: {
      nano: {
        src: ['<%= dirs.coffeeDir %>/*.coffee'],
        dest: '<%= dirs.jsDir %>',
        options: {
            bare: true
        }
      },
      tests: {
        src: ['<%= dirs.testDir %>/coffeescripts/*.coffee'],
        dest: '<%= dirs.testDir %>/spec'
      }
    },
    min: {
      all: {
        src: ['<%= dirs.jsDir %>/<%= pkg.name %>.js'],
        dest: '<%= dirs.jsDir %>/<%= pkg.name %>.min.js'
      }
    },
    sizediff: {
      all: {
        files: [
            '<%= dirs.jsDir %>/<%= pkg.name %>.js',
            '<%= dirs.jsDir %>/<%= pkg.name %>.min.js'
        ]
      }
    },
    jasmine: {
      all: ['<%= dirs.testDir %>/SpecRunner.html']
    },
    lint: {
      files: ['grunt.js']
    },
    watch: {
      files: '<config:coffee.nano.src>',
      tasks: 'default'
    },
    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        boss: true,
        eqnull: true,
        browser: true
      },
      globals: {
        jQuery: true
      }
    },
    shell: {
      marked: {
        command: 'node_modules/marked/bin/marked README.md > bin/readme.html',
        stdout: true
      }
    },
    yuidoc: {
      compile: {
        options: {
          paths: "bin/javascripts",
          outdir: "docs/"
        }
      }
    }
  });

  grunt.registerTask('default', 'coffee:nano min concat:unmin concat:min csslint lint sizediff shell:marked yuidoc');
  grunt.registerTask('build', 'default');
  grunt.registerTask('build:tests', 'coffee:tests');
  grunt.registerTask('test', 'coffee:tests jasmine');
  grunt.registerTask('size', 'sizediff');
};
<commit_msg>Remove YUIDoc from default grunt task, add build:docs task<commit_after>/*global module:false*/
module.exports = function(grunt) {
  grunt.loadNpmTasks('grunt-contrib-yuidoc');
  grunt.loadNpmTasks('grunt-jasmine-task');
  grunt.loadNpmTasks('grunt-coffee');
  grunt.loadNpmTasks('grunt-css');
  grunt.loadNpmTasks('grunt-sizediff');
  grunt.loadNpmTasks('grunt-shell');

  // Project configuration.
  grunt.initConfig({
    dirs: {
      coffeeDir: 'coffeescripts',
      jsDir: 'bin/javascripts',
      cssDir: 'bin/css',
      testDir: 'tests'
    },
    pkg: '<json:nanoscroller.jquery.json>',
    meta: {
      unmin: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %>\n' +
        '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +
        '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
        ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */',
      min: '/*! <%= pkg.title || pkg.name %> v<%= pkg.version %> ' +
        '(c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
        ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
    },
    concat: {
      unmin: {
        src: ['<banner:meta.unmin>', '<file_strip_banner:bin/javascripts/<%= pkg.name %>.js>'],
        dest: '<%= dirs.jsDir %>/<%= pkg.name %>.js'
      },
      min: {
        src: ['<banner:meta.min>', '<file_strip_banner:bin/javascripts/<%= pkg.name %>.min.js>'],
        dest: '<%= dirs.jsDir %>/<%= pkg.name %>.min.js'
      }
    },
    csslint: {
      all: {
        src: '<%= dirs.cssDir %>/nanoscroller.css',
        rules: {
            'fallback-colors': false,
            'known-properties': false,
            'compatible-vendor-prefixes': false,
            'adjoining-classes': false,
            'empty-rules': true,
            'zero-units': true,
            ids: true,
            important: true
        }
      }
    },
    coffee: {
      nano: {
        src: ['<%= dirs.coffeeDir %>/*.coffee'],
        dest: '<%= dirs.jsDir %>',
        options: {
            bare: true
        }
      },
      tests: {
        src: ['<%= dirs.testDir %>/coffeescripts/*.coffee'],
        dest: '<%= dirs.testDir %>/spec'
      }
    },
    min: {
      all: {
        src: ['<%= dirs.jsDir %>/<%= pkg.name %>.js'],
        dest: '<%= dirs.jsDir %>/<%= pkg.name %>.min.js'
      }
    },
    sizediff: {
      all: {
        files: [
            '<%= dirs.jsDir %>/<%= pkg.name %>.js',
            '<%= dirs.jsDir %>/<%= pkg.name %>.min.js'
        ]
      }
    },
    jasmine: {
      all: ['<%= dirs.testDir %>/SpecRunner.html']
    },
    lint: {
      files: ['grunt.js']
    },
    watch: {
      files: '<config:coffee.nano.src>',
      tasks: 'default'
    },
    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        boss: true,
        eqnull: true,
        browser: true
      },
      globals: {
        jQuery: true
      }
    },
    shell: {
      marked: {
        command: 'node_modules/marked/bin/marked README.md > bin/readme.html',
        stdout: true
      }
    },
    yuidoc: {
      compile: {
        options: {
          paths: "bin/javascripts",
          outdir: "docs/"
        }
      }
    }
  });

  grunt.registerTask('default', 'coffee:nano min concat:unmin concat:min csslint lint sizediff shell:marked');
  grunt.registerTask('build', 'default');
  grunt.registerTask('build:tests', 'coffee:tests');
  grunt.registerTask('build:docs', 'yuidoc');
  grunt.registerTask('test', 'coffee:tests jasmine');
  grunt.registerTask('size', 'sizediff');
};
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2009 Sprout Systems, Inc. and contributors.
//            Portions ©2008-2009 Apple, Inc. All rights reserved.
// License:   Licened under MIT license (see license.js)
// ==========================================================================

/**
  @class

  The UserDefaults object provides an easy way to store user preferences in
  your application on the local machine.  You use this by providing built-in
  defaults using the SC.userDefaults.defaults() method.  You can also
  implement the UserDefaultsDelegate interface to be notified whenever a
  default is required.

  You should also set the userDomain property on the defaults on page load.
  This will allow the UserDefaults application to store/fetch keys from
  localStorage for the correct user.

  You can also set an appDomain property if you want.  This will be
  automatically prepended to key names with no slashes in them.

  SC.userDefaults.getPath("global:contactInfo.userName");

  @extends SC.Object
  @since SproutCore 1.0
*/
SC.UserDefaults = SC.Object.extend(/** @scope SC.UserDefaults.prototype */ {

  /**
    the default domain for the user.  This will be used to store keys in
    local storage.  If you do not set this property, the wrong values may be
    returned.
  */
  userDomain: null,

  /**
    The default app domain for the user.  Any keys that do not include a
    slash will be prefixed with this app domain key when getting/setting.
  */
  appDomain: null,

  /** @private
    Defaults.  These will be used if not defined on localStorage.
  */
  _defaults: null,

  /**
    Invoke this method to set the builtin defaults.  This will cause all
    properties to change.
  */
  defaults: function(newDefaults) {
    this._defaults = newDefaults ;
    this.allPropertiesDidChange();
  },

  /**
    Attempts to read a user default from local storage.  If not found on
    localStorage, use the the local defaults, if defined.  If the key passed
    does not include a slash, then add the appDomain or use "app/".

    @param {String} keyName
    @returns {Object} read value
  */
  readDefault: function(keyName) {
    var ret= undefined ;

    // namespace keyname
    if (keyName.indexOf('/')) {
      var domain = this.get('appDomain') || 'app';
      keyName = [domain, keyName].join(':');
    }

    var user = this.get('userDomain') || '' ;
    var userKeyName = [user,keyName].join('@');

    // look into recently written values
    if (this._written) ret = this._written[userKeyName];

    // attempt to read from localStorage
    var localStorage = window.localStorage ;
    if (!localStorage && window.globalStorage) {
      localStorage = window.globalStorage[window.location.hostname];
    }
    if (localStorage) {
      console.log('userKeyName = %@ local=%@'.fmt(userKeyName, localStorage));
      ret = localStorage[["SC.UserDefaults",userKeyName].join('@')];
    }

    // if not found in localStorage, try to notify delegate
    var del =this.delegate ;
    if (del && del.userDefaultsNeedsDefault) {
      ret = del.userDefaultsNeedsDefault(this, keyName, userKeyName);
    }

    // if not found in localStorage or delegate, try to find in defaults
    if ((ret===undefined) && this._defaults) {
      ret = this._defaults[userKeyName] || this._defaults[keyName];
    }

    return ret ;
  },

  /**
    Attempts to write the user default to local storage or at least saves them
    for now.  Also notifies that the value has changed.

    @param {String} keyName
    @param {Object} value
    @returns {SC.UserDefault} receiver
  */
  writeDefault: function(keyName, value) {
    // namespace keyname
    if (keyName.indexOf('/')) {
      var domain = this.get('appDomain') || 'app';
      keyName = [domain, keyName].join(':');
    }

    var user = this.get('userDomain') || '' ;
    var userKeyName = [user,keyName].join('@');

    // save to local hash
    var written = this._written ;
    if (!written) written = this._written = {};
    written[userKeyName] = value ;

    // save to local storage
    var localStorage = window.localStorage ;
    if (!localStorage && window.globalStorage) {
      localStorage = window.globalStorage[window.location.hostname];
    }
    if (localStorage) {
      localStorage[["SC.UserDefaults",userKeyName].join('@')] = value;
    }

    // also notify delegate
    var del = this.delegate;
    if (del && del.userDefaultsDidChange) {
      del.userDefaultsDidChange(this, keyName, value, userKeyName);
    }

    return this ;
  },

  unknownProperty: function(key, value) {
    if (value === undefined) {
      return this.readDefault(key) ;
    } else {
      this.writeDefault(key, value);
      return value ;
    }
  }

});

/** global user defaults. */
SC.userDefaults = SC.UserDefaults.create();<commit_msg>comment fmt function used for console.log failing in IE<commit_after>// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2009 Sprout Systems, Inc. and contributors.
//            Portions ©2008-2009 Apple, Inc. All rights reserved.
// License:   Licened under MIT license (see license.js)
// ==========================================================================

/**
  @class

  The UserDefaults object provides an easy way to store user preferences in
  your application on the local machine.  You use this by providing built-in
  defaults using the SC.userDefaults.defaults() method.  You can also
  implement the UserDefaultsDelegate interface to be notified whenever a
  default is required.

  You should also set the userDomain property on the defaults on page load.
  This will allow the UserDefaults application to store/fetch keys from
  localStorage for the correct user.

  You can also set an appDomain property if you want.  This will be
  automatically prepended to key names with no slashes in them.

  SC.userDefaults.getPath("global:contactInfo.userName");

  @extends SC.Object
  @since SproutCore 1.0
*/
SC.UserDefaults = SC.Object.extend(/** @scope SC.UserDefaults.prototype */ {

  /**
    the default domain for the user.  This will be used to store keys in
    local storage.  If you do not set this property, the wrong values may be
    returned.
  */
  userDomain: null,

  /**
    The default app domain for the user.  Any keys that do not include a
    slash will be prefixed with this app domain key when getting/setting.
  */
  appDomain: null,

  /** @private
    Defaults.  These will be used if not defined on localStorage.
  */
  _defaults: null,

  /**
    Invoke this method to set the builtin defaults.  This will cause all
    properties to change.
  */
  defaults: function(newDefaults) {
    this._defaults = newDefaults ;
    this.allPropertiesDidChange();
  },

  /**
    Attempts to read a user default from local storage.  If not found on
    localStorage, use the the local defaults, if defined.  If the key passed
    does not include a slash, then add the appDomain or use "app/".

    @param {String} keyName
    @returns {Object} read value
  */
  readDefault: function(keyName) {
    var ret= undefined ;

    // namespace keyname
    if (keyName.indexOf('/')) {
      var domain = this.get('appDomain') || 'app';
      keyName = [domain, keyName].join(':');
    }

    var user = this.get('userDomain') || '' ;
    var userKeyName = [user,keyName].join('@');

    // look into recently written values
    if (this._written) ret = this._written[userKeyName];

    // attempt to read from localStorage
    var localStorage = window.localStorage ;
    if (!localStorage && window.globalStorage) {
      localStorage = window.globalStorage[window.location.hostname];
    }
    if (localStorage) {
      //console.log('userKeyName = %@ local=%@'.fmt(userKeyName, localStorage));
      ret = localStorage[["SC.UserDefaults",userKeyName].join('@')];
    }

    // if not found in localStorage, try to notify delegate
    var del =this.delegate ;
    if (del && del.userDefaultsNeedsDefault) {
      ret = del.userDefaultsNeedsDefault(this, keyName, userKeyName);
    }

    // if not found in localStorage or delegate, try to find in defaults
    if ((ret===undefined) && this._defaults) {
      ret = this._defaults[userKeyName] || this._defaults[keyName];
    }

    return ret ;
  },

  /**
    Attempts to write the user default to local storage or at least saves them
    for now.  Also notifies that the value has changed.

    @param {String} keyName
    @param {Object} value
    @returns {SC.UserDefault} receiver
  */
  writeDefault: function(keyName, value) {
    // namespace keyname
    if (keyName.indexOf('/')) {
      var domain = this.get('appDomain') || 'app';
      keyName = [domain, keyName].join(':');
    }

    var user = this.get('userDomain') || '' ;
    var userKeyName = [user,keyName].join('@');

    // save to local hash
    var written = this._written ;
    if (!written) written = this._written = {};
    written[userKeyName] = value ;

    // save to local storage
    var localStorage = window.localStorage ;
    if (!localStorage && window.globalStorage) {
      localStorage = window.globalStorage[window.location.hostname];
    }
    if (localStorage) {
      localStorage[["SC.UserDefaults",userKeyName].join('@')] = value;
    }

    // also notify delegate
    var del = this.delegate;
    if (del && del.userDefaultsDidChange) {
      del.userDefaultsDidChange(this, keyName, value, userKeyName);
    }

    return this ;
  },

  unknownProperty: function(key, value) {
    if (value === undefined) {
      return this.readDefault(key) ;
    } else {
      this.writeDefault(key, value);
      return value ;
    }
  }

});

/** global user defaults. */
SC.userDefaults = SC.UserDefaults.create();<|endoftext|>


<commit_before>// New copy task for font files and config.json.
module.exports = {
  // Override Ionic copyFonts task to exclude Roboto and Noto fonts.
  copyFonts: {
    src: ['{{ROOT}}/node_modules/ionicons/dist/fonts/**/*'],
    dest: '{{WWW}}/assets/fonts'
  },
  copyFontAwesome: {
    src: ['{{ROOT}}/node_modules/font-awesome/fonts/**/*'],
    dest: '{{WWW}}/assets/fonts'
  },
  copyConfig: {
    src: ['{{ROOT}}/src/config.json'],
    dest: '{{WWW}}/'
  },
  copyMathJaxMain: {
    src: ['{{ROOT}}/node_modules/mathjax/MathJax.js'],
    dest: '{{WWW}}/lib/mathjax'
  },
  copyMathJaxExtensions: {
    src: ['{{ROOT}}/node_modules/mathjax/extensions/**/*'],
    dest: '{{WWW}}/lib/mathjax/extensions'
  },
  copyMathJaxElement: {
    src: ['{{ROOT}}/node_modules/mathjax/jax/element/**/*'],
    dest: '{{WWW}}/lib/mathjax/jax/element'
  },
  copyMathJaxInput: {
    src: ['{{ROOT}}/node_modules/mathjax/jax/input/**/*'],
    dest: '{{WWW}}/lib/mathjax/jax/input'
  },
  copyMathJaxOutput: {
    src: ['{{ROOT}}/node_modules/mathjax/jax/output/SVG/**/*'],
    dest: '{{WWW}}/lib/mathjax/jax/output/SVG'
  },
  copyMathJaxLocalization: {
    src: ['{{ROOT}}/node_modules/mathjax/localization/**/*'],
    dest: '{{WWW}}/lib/mathjax/localization'
  },
};
<commit_msg>MOBILE-3232 filters: Add PreviewHTML mathjax output<commit_after>// New copy task for font files and config.json.
module.exports = {
  // Override Ionic copyFonts task to exclude Roboto and Noto fonts.
  copyFonts: {
    src: ['{{ROOT}}/node_modules/ionicons/dist/fonts/**/*'],
    dest: '{{WWW}}/assets/fonts'
  },
  copyFontAwesome: {
    src: ['{{ROOT}}/node_modules/font-awesome/fonts/**/*'],
    dest: '{{WWW}}/assets/fonts'
  },
  copyConfig: {
    src: ['{{ROOT}}/src/config.json'],
    dest: '{{WWW}}/'
  },
  copyMathJaxMain: {
    src: ['{{ROOT}}/node_modules/mathjax/MathJax.js'],
    dest: '{{WWW}}/lib/mathjax'
  },
  copyMathJaxExtensions: {
    src: ['{{ROOT}}/node_modules/mathjax/extensions/**/*'],
    dest: '{{WWW}}/lib/mathjax/extensions'
  },
  copyMathJaxElement: {
    src: ['{{ROOT}}/node_modules/mathjax/jax/element/**/*'],
    dest: '{{WWW}}/lib/mathjax/jax/element'
  },
  copyMathJaxInput: {
    src: ['{{ROOT}}/node_modules/mathjax/jax/input/**/*'],
    dest: '{{WWW}}/lib/mathjax/jax/input'
  },
  copyMathJaxSVGOutput: {
    src: ['{{ROOT}}/node_modules/mathjax/jax/output/SVG/**/*'],
    dest: '{{WWW}}/lib/mathjax/jax/output/SVG'
  },
  copyMathJaxPreviewHTMLOutput: {
    src: ['{{ROOT}}/node_modules/mathjax/jax/output/PreviewHTML/**/*'],
    dest: '{{WWW}}/lib/mathjax/jax/output/PreviewHTML'
  },
  copyMathJaxLocalization: {
    src: ['{{ROOT}}/node_modules/mathjax/localization/**/*'],
    dest: '{{WWW}}/lib/mathjax/localization'
  },
};
<|endoftext|>


<commit_before>let r = require('rethinkdbdash')();
let readline = require('readline');

let rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

// Display stuff from the chat
r.table('Message').changes().run().then((cursor) => {
  cursor.each((err, change) => {
    let message = change.new_val;
    if (message) {
      console.log(message.content, message.time);
    }
  });
});

// Typing stuff in should create a new message
rl.on('line', (content) => {
  let time = new Date();
  console.log('inserting ' + content);
  r.table('Message').insert({content, time}).run().done();
});

// TODO: make live-listening work
<commit_msg>remove pointless log statement<commit_after>let r = require('rethinkdbdash')();
let readline = require('readline');

let rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

// Display stuff from the chat
r.table('Message').changes().run().then((cursor) => {
  cursor.each((err, change) => {
    let message = change.new_val;
    if (message) {
      console.log(message.content, message.time);
    }
  });
});

// Typing stuff in should create a new message
rl.on('line', (content) => {
  let time = new Date();
  r.table('Message').insert({content, time}).run().done();
});

// TODO: make live-listening work
<|endoftext|>


<commit_before>"use strict";

var request = require("request");
const EventEmitter = require("events");

var ThermostatItem = function(widget,platform,homebridge) {
    //General
    this.temperatureDisplayUnits = homebridge.hap.Characteristic.TemperatureDisplayUnits.FAHRENHEIT;
    this.thermostatItemEmitter = new EventEmitter();
    this.initEmitter();

    //CurrentTemperature
    this.itemCurrentTemperature = undefined;
    this.listenerCurrentTemperature = undefined;
    this.wsCurrentTemperature = undefined;

    //TargetTemperature
    this.itemTargetTemperature = undefined;
    this.setTargetTemperatureInitialState = false;
    this.targetTemperatureArr = [];
    this.targetTemperatureInProgress = false;
    this.targetTemperatureTimeout = 1000;

    //CurrentHeatingCoolingState
    this.itemCurrentHeatingCoolingState = undefined;
    this.listenerCurrentHeatingCoolingState = undefined;
    this.wsCurrentHeatingCoolingState = undefined;

    //TargetHeatingCoolingState
    this.itemTargetHeatingCoolingState = undefined;
    this.listenerTargetHeatingCoolingState = undefined;
    this.wsTargetHeatingCoolingState = undefined;

    //CoolingThresholdTemperature
    this.itemCoolingThresholdTemperature = undefined;
    this.listenerCoolingThresholdTemperature = undefined;
    this.wsCoolingThresholdTemperature = undefined;

    //HeatingThresholdTemperature
    this.itemHeatingThresholdTemperature = undefined;
    this.listenerHeatingThresholdTemperature = undefined;
    this.wsHeatingThresholdTemperature = undefined;

    ThermostatItem.super_.call(this, widget,platform,homebridge);
};

//CurrentTemperature
ThermostatItem.prototype.setCurrentTemperatureItem = function(item){
    this.itemCurrentTemperature = item;
    this.temperatureDisplayUnits = this.homebridge.hap.Characteristic.TemperatureDisplayUnits.CELSIUS;
};
//TargetHeatingCoolingState
ThermostatItem.prototype.setTargetHeatingCoolingStateItem = function(item){
    this.itemTargetHeatingCoolingState = item;
};
//CoolingThresholdTemperature
ThermostatItem.prototype.setCoolingThresholdTemperatureItem = function(item){
    this.itemCoolingThresholdTemperature = item;
};
//HeatingThresholdTemperature
ThermostatItem.prototype.setHeatingThresholdTemperatureItem = function(item){
    this.itemHeatingThresholdTemperature = item;
};

ThermostatItem.prototype.initEmitter = function() {
    var self=this;
    this.thermostatItemEmitter.on('TARGET_TEMPERATURE_UPDATE_EVENT', function() {
        self.setTargetTemperatureStateFromEmit();
    });
};

/**
 * Init all thermostat listener
 */
ThermostatItem.prototype.initListener = function() {
    if ((typeof this.itemCurrentTemperature) == 'undefined'){
        throw new Error(this.name + " needs CurrentTemperatureItem!");
    }

    //CurrentTemperature
    this.listenerCurrentTemperature = this.listenerFactory(
        this.itemCurrentTemperature.name,
        this.itemCurrentTemperature.link,
        this.wsCurrentTemperature,
        this.log,
        this.updateCurrentTemperature.bind(this)
    );

    //TargetHeatingCoolingState
    this.listenerTargetHeatingCoolingState = this.listenerFactory(
        this.itemTargetHeatingCoolingState.name,
        this.itemTargetHeatingCoolingState.link,
        this.wsTargetHeatingCoolingState,
        this.log,
        this.updateTargetHeatingCoolingState.bind(this)
    );

    //CoolingThresholdTemperature
    this.listenerCoolingThresholdTemperature = this.listenerFactory(
        this.itemCoolingThresholdTemperature.name,
        this.itemCoolingThresholdTemperature.link,
        this.wsCoolingThresholdTemperature,
        this.log,
        this.updateCoolingThresholdTemperature.bind(this)
    );

    //HeatingThresholdTemperature
    this.listenerHeatingThresholdTemperature = this.listenerFactory(
        this.itemHeatingThresholdTemperature.name,
        this.itemHeatingThresholdTemperature.link,
        this.wsHeatingThresholdTemperature,
        this.log,
        this.updateHeatingThresholdTemperature.bind(this)
    );
};

/**
 * Initiialize Others Services needed for ThermostatItem
 * @returns {*}
 */
ThermostatItem.prototype.getOtherServices = function() {
    var otherService = new this.homebridge.hap.Service.Thermostat();

    //Init CurrentTemperature Characteristic
    otherService.getCharacteristic(this.homebridge.hap.Characteristic.CurrentTemperature)
        .on('get', this.getCurrentTemperatureState.bind(this))
        .setValue(this.checkTemperatureState(this.itemCurrentTemperature.state));

    //Init TargetTemperature Characteristic
    otherService.getCharacteristic(this.homebridge.hap.Characteristic.TargetTemperature)
        .on('get', this.getCurrentTemperatureState.bind(this))
        .setValue(this.checkTemperatureState(this.itemCurrentTemperature.state));

    //Init CurrentHeatingCoolingState Characteristic
    otherService.getCharacteristic(this.homebridge.hap.Characteristic.CurrentHeatingCoolingState)
        .on('get', this.getCurrentHeatingCoolingState.bind(this))
        .setValue(this.checkCurrentHeatingCoolingState(this.itemTargetHeatingCoolingState.state));

    //Init TargetHeatingCoolingState Characteristic
    otherService.getCharacteristic(this.homebridge.hap.Characteristic.TargetHeatingCoolingState)
        .on('set', this.setTargetHeatingCoolingState.bind(this))
        .on('get', this.getTargetHeatingCoolingState.bind(this))
        .setValue(this.checkTargetHeatingCoolingState(this.itemTargetHeatingCoolingState.state));

    //Init CoolingThresholdTemperature Characteristic
    otherService.getCharacteristic(this.homebridge.hap.Characteristic.CoolingThresholdTemperature)
        .on('set', this.setCoolingThresholdTemperature.bind(this))
        .on('get', this.getCoolingThresholdTemperature.bind(this))
        .setValue(this.checkTemperatureState(this.itemCoolingThresholdTemperature.state));

    //Init HeatingThresholdTemperature Characteristic
    otherService.getCharacteristic(this.homebridge.hap.Characteristic.HeatingThresholdTemperature)
        .on('set', this.setHeatingThresholdTemperature.bind(this))
        .on('get', this.getHeatingThresholdTemperature.bind(this))
        .setValue(this.checkTemperatureState(this.itemHeatingThresholdTemperature.state));

    otherService.getCharacteristic(this.homebridge.hap.Characteristic.TemperatureDisplayUnits)
        .on('get', this.getTemperatureDisplayUnits.bind(this))
        .setValue(this.temperatureDisplayUnits);

    return otherService;
};

//CurrentTemperature
ThermostatItem.prototype.updateCurrentTemperature = function(message) {
    this.otherService
        .getCharacteristic(this.homebridge.hap.Characteristic.CurrentTemperature)
        .setValue(this.checkTemperatureState(message));
};
ThermostatItem.prototype.getCurrentTemperatureState = function(callback) {
    var self = this;
    this.log("iOS - request current temperature state from " + this.itemCurrentTemperature.name + " (" + (self.name)+")");
    request(self.itemCurrentTemperature.link + '/state?type=json', function (error, response, body) {
        if (!error && response.statusCode == 200) {
            self.log("OpenHAB HTTP - response from " + self.itemCurrentTemperature.name + " (" + (self.name)+"): " + body);
            callback(undefined,self.checkTemperatureState(body));
        } else {
            self.log("OpenHAB HTTP - error from " + self.itemCurrentTemperature.name + " (" + (self.name)+"): " + error);
        }
    })
};

//CurrentHeatingCoolingState
ThermostatItem.prototype.getCurrentHeatingCoolingState = function(callback) {
    var self = this;
    this.log("iOS - request Current Heating/Cooling State state from " + this.itemTargetHeatingCoolingState.name + " (" + (self.name)+")");
    request(self.itemTargetHeatingCoolingState.link + '/state?type=json', function (error, response, body) {
        if (!error && response.statusCode == 200) {
            self.log("OpenHAB HTTP - response from " + self.itemTargetHeatingCoolingState.name + " (" + (self.name)+"): " + body);
            callback(undefined,self.checkCurrentHeatingCoolingState(body));
        } else {
            self.log("OpenHAB HTTP - error from " + self.itemTargetHeatingCoolingState.name + " (" + (self.name)+"): " + error);
        }
    })
};

//TargetHeatingCoolingState
ThermostatItem.prototype.updateTargetHeatingCoolingState = function(message) {
    this.otherService
        .getCharacteristic(this.homebridge.hap.Characteristic.TargtHeatingCoolingState)
        .setValue(this.checkTargetHeatingCoolingState(message));
    this.otherService
        .getCharacteristic(this.homebridge.hap.Characteristic.CurrentHeatingCoolingState)
        .setValue(this.checkCurrentHeatingCoolingState(message));
};
ThermostatItem.prototype.getTargetHeatingCoolingState = function(callback) {
    var self = this;
    this.log("iOS - request Target Heating/Cooling State from " + this.itemTargetHeatingCoolingState.name + " (" + (self.name)+")");
    request(self.itemTargetHeatingCoolingState.link + '/state?type=json', function (error, response, body) {
        if (!error && response.statusCode == 200) {
            self.log("OpenHAB HTTP - response from " + self.itemTargetHeatingCoolingState.name + " (" + (self.name)+"): " + body);
            callback(undefined,self.checkTargetHeatingCoolingState(body));
        } else {
            self.log("OpenHAB HTTP - error from " + self.itemTargetHeatingCoolingState.name + " (" + (self.name)+"): " + error);
        }
    })
};
ThermostatItem.prototype.setTargetHeatingCoolingState = function(value,callback) {
    callback();
};

//CoolingThresholdTemperature
ThermostatItem.prototype.updateCoolingThresholdTemperature = function(message) {
    this.otherService
        .getCharacteristic(this.homebridge.hap.Characteristic.CoolingThresholdTemperature)
        .setValue(this.checkTemperatureState(message));
};
ThermostatItem.prototype.getCoolingThresholdTemperature = function(callback) {
    var self = this;
    this.log("iOS - request Cooling Threshold Temperature state from " + this.itemCoolingThresholdTemperature.name + " (" + (self.name)+")");
    request(self.itemCoolingThresholdTemperature.link + '/state?type=json', function (error, response, body) {
        if (!error && response.statusCode == 200) {
            self.log("OpenHAB HTTP - response from " + self.itemCoolingThresholdTemperature.name + " (" + (self.name)+"): " + body);
            callback(undefined,self.checkTemperatureState(body));
        } else {
            self.log("OpenHAB HTTP - error from " + self.itemCoolingThresholdTemperature.name + " (" + (self.name)+"): " + error);
        }
    })
};
ThermostatItem.prototype.setCoolingThresholdTemperature = function(value,callback) {
    // var self = this;
    // //
    // // if (this.setInitialState) {
    // //     this.setInitialState = false;
    // //     callback();
    // //     return;
    // // }
    // //
    // // if (this.setFromOpenHAB) {
    // //     callback();
    // //     return;
    // // }
    //
    // this.log("iOS - send message to " + this.itemCoolingThresholdTemperature.name + ": " + value);
    // var command = value;
    // request.post(
    //     this.itemTargetDoorState.link,
    //     {
    //         body: command,
    //         headers: {'Content-Type': 'text/plain'}
    //     },
    //     function (error, response, body) {
    //         if (!error && response.statusCode == 201) {
    //             self.log("OpenHAB HTTP - response from " + self.itemCoolingThresholdTemperature.name + ": " + body);
    //         } else {
    //             self.log("OpenHAB HTTP - error from " + self.itemCoolingThresholdTemperature.name + ": " + error);
    //         }
    //         callback();
    //     }
    // );
    callback();
}

//HeatingThresholdTemperature
ThermostatItem.prototype.updateHeatingThresholdTemperature = function(message) {
    this.otherService
        .getCharacteristic(this.homebridge.hap.Characteristic.HeatingThresholdTemperature)
        .setValue(this.checkTemperatureState(message));
};
ThermostatItem.prototype.getHeatingThresholdTemperature = function(callback) {
    var self = this;
    this.log("iOS - request Heating Threshold Temperature state from " + this.itemHeatingThresholdTemperature.name + " (" + (self.name)+")");
    request(self.itemHeatingThresholdTemperature.link + '/state?type=json', function (error, response, body) {
        if (!error && response.statusCode == 200) {
            self.log("OpenHAB HTTP - response from " + self.itemHeatingThresholdTemperature.name + " (" + (self.name)+"): " + body);
            callback(undefined,self.checkTemperatureState(body));
        } else {
            self.log("OpenHAB HTTP - error from " + self.itemHeatingThresholdTemperature.name + " (" + (self.name)+"): " + error);
        }
    })
};
ThermostatItem.prototype.setHeatingThresholdTemperature = function(value, callback) {
    callback();
}

ThermostatItem.prototype.getTemperatureDisplayUnits = function(callback) {
    callback(undefined,this.temperatureDisplayUnits);
};

ThermostatItem.prototype.checkTemperatureState = function(state) {
    if ('Unitialized' === state){
        return 20.0;
    }
    return +state;
};

ThermostatItem.prototype.checkTargetHeatingCoolingState = function(state) {
    switch (state){
        case 0:
            return this.homebridge.hap.Characteristic.TargetHeatingCoolingState.OFF;
        case 1:
            return this.homebridge.hap.Characteristic.TargetHeatingCoolingState.HEAT;
        case 2:
            return this.homebridge.hap.Characteristic.TargetHeatingCoolingState.COOL;
        case 3:
            return this.homebridge.hap.Characteristic.TargetHeatingCoolingState.AUTO;
        default:
            return this.homebridge.hap.Characteristic.TargetHeatingCoolingState.OFF;
    }
};

ThermostatItem.prototype.checkCurrentHeatingCoolingState = function(state) {
    switch (state){
        case 0:
            return this.homebridge.hap.Characteristic.CurrentHeatingCoolingState.OFF;
        case 1:
            return this.homebridge.hap.Characteristic.CurrentHeatingCoolingState.HEAT;
        case 2:
            return this.homebridge.hap.Characteristic.CurrentHeatingCoolingState.COOL;
        case 3:
            return this.homebridge.hap.Characteristic.CurrentHeatingCoolingState.OFF;
        default:
            return this.homebridge.hap.Characteristic.CurrentHeatingCoolingState.OFF;
    }
};

/**
 * Export ThermostatItem
 * @type {ThermostatItem}
 */
module.exports = ThermostatItem;
<commit_msg>switch needed strings not ints<commit_after>"use strict";

var request = require("request");
const EventEmitter = require("events");

var ThermostatItem = function(widget,platform,homebridge) {
    //General
    this.temperatureDisplayUnits = homebridge.hap.Characteristic.TemperatureDisplayUnits.FAHRENHEIT;
    this.thermostatItemEmitter = new EventEmitter();
    this.initEmitter();

    //CurrentTemperature
    this.itemCurrentTemperature = undefined;
    this.listenerCurrentTemperature = undefined;
    this.wsCurrentTemperature = undefined;

    //TargetTemperature
    this.itemTargetTemperature = undefined;
    this.setTargetTemperatureInitialState = false;
    this.targetTemperatureArr = [];
    this.targetTemperatureInProgress = false;
    this.targetTemperatureTimeout = 1000;

    //CurrentHeatingCoolingState
    this.itemCurrentHeatingCoolingState = undefined;
    this.listenerCurrentHeatingCoolingState = undefined;
    this.wsCurrentHeatingCoolingState = undefined;

    //TargetHeatingCoolingState
    this.itemTargetHeatingCoolingState = undefined;
    this.listenerTargetHeatingCoolingState = undefined;
    this.wsTargetHeatingCoolingState = undefined;

    //CoolingThresholdTemperature
    this.itemCoolingThresholdTemperature = undefined;
    this.listenerCoolingThresholdTemperature = undefined;
    this.wsCoolingThresholdTemperature = undefined;

    //HeatingThresholdTemperature
    this.itemHeatingThresholdTemperature = undefined;
    this.listenerHeatingThresholdTemperature = undefined;
    this.wsHeatingThresholdTemperature = undefined;

    ThermostatItem.super_.call(this, widget,platform,homebridge);
};

//CurrentTemperature
ThermostatItem.prototype.setCurrentTemperatureItem = function(item){
    this.itemCurrentTemperature = item;
    this.temperatureDisplayUnits = this.homebridge.hap.Characteristic.TemperatureDisplayUnits.CELSIUS;
};
//TargetHeatingCoolingState
ThermostatItem.prototype.setTargetHeatingCoolingStateItem = function(item){
    this.itemTargetHeatingCoolingState = item;
};
//CoolingThresholdTemperature
ThermostatItem.prototype.setCoolingThresholdTemperatureItem = function(item){
    this.itemCoolingThresholdTemperature = item;
};
//HeatingThresholdTemperature
ThermostatItem.prototype.setHeatingThresholdTemperatureItem = function(item){
    this.itemHeatingThresholdTemperature = item;
};

ThermostatItem.prototype.initEmitter = function() {
    var self=this;
    this.thermostatItemEmitter.on('TARGET_TEMPERATURE_UPDATE_EVENT', function() {
        self.setTargetTemperatureStateFromEmit();
    });
};

/**
 * Init all thermostat listener
 */
ThermostatItem.prototype.initListener = function() {
    if ((typeof this.itemCurrentTemperature) == 'undefined'){
        throw new Error(this.name + " needs CurrentTemperatureItem!");
    }

    //CurrentTemperature
    this.listenerCurrentTemperature = this.listenerFactory(
        this.itemCurrentTemperature.name,
        this.itemCurrentTemperature.link,
        this.wsCurrentTemperature,
        this.log,
        this.updateCurrentTemperature.bind(this)
    );

    //TargetHeatingCoolingState
    this.listenerTargetHeatingCoolingState = this.listenerFactory(
        this.itemTargetHeatingCoolingState.name,
        this.itemTargetHeatingCoolingState.link,
        this.wsTargetHeatingCoolingState,
        this.log,
        this.updateTargetHeatingCoolingState.bind(this)
    );

    //CoolingThresholdTemperature
    this.listenerCoolingThresholdTemperature = this.listenerFactory(
        this.itemCoolingThresholdTemperature.name,
        this.itemCoolingThresholdTemperature.link,
        this.wsCoolingThresholdTemperature,
        this.log,
        this.updateCoolingThresholdTemperature.bind(this)
    );

    //HeatingThresholdTemperature
    this.listenerHeatingThresholdTemperature = this.listenerFactory(
        this.itemHeatingThresholdTemperature.name,
        this.itemHeatingThresholdTemperature.link,
        this.wsHeatingThresholdTemperature,
        this.log,
        this.updateHeatingThresholdTemperature.bind(this)
    );
};

/**
 * Initiialize Others Services needed for ThermostatItem
 * @returns {*}
 */
ThermostatItem.prototype.getOtherServices = function() {
    var otherService = new this.homebridge.hap.Service.Thermostat();

    //Init CurrentTemperature Characteristic
    otherService.getCharacteristic(this.homebridge.hap.Characteristic.CurrentTemperature)
        .on('get', this.getCurrentTemperatureState.bind(this))
        .setValue(this.checkTemperatureState(this.itemCurrentTemperature.state));

    //Init TargetTemperature Characteristic
    otherService.getCharacteristic(this.homebridge.hap.Characteristic.TargetTemperature)
        .on('get', this.getCurrentTemperatureState.bind(this))
        .setValue(this.checkTemperatureState(this.itemCurrentTemperature.state));

    //Init CurrentHeatingCoolingState Characteristic
    otherService.getCharacteristic(this.homebridge.hap.Characteristic.CurrentHeatingCoolingState)
        .on('get', this.getCurrentHeatingCoolingState.bind(this))
        .setValue(this.checkCurrentHeatingCoolingState(this.itemTargetHeatingCoolingState.state));

    //Init TargetHeatingCoolingState Characteristic
    otherService.getCharacteristic(this.homebridge.hap.Characteristic.TargetHeatingCoolingState)
        .on('set', this.setTargetHeatingCoolingState.bind(this))
        .on('get', this.getTargetHeatingCoolingState.bind(this))
        .setValue(this.checkTargetHeatingCoolingState(this.itemTargetHeatingCoolingState.state));

    //Init CoolingThresholdTemperature Characteristic
    otherService.getCharacteristic(this.homebridge.hap.Characteristic.CoolingThresholdTemperature)
        .on('set', this.setCoolingThresholdTemperature.bind(this))
        .on('get', this.getCoolingThresholdTemperature.bind(this))
        .setValue(this.checkTemperatureState(this.itemCoolingThresholdTemperature.state));

    //Init HeatingThresholdTemperature Characteristic
    otherService.getCharacteristic(this.homebridge.hap.Characteristic.HeatingThresholdTemperature)
        .on('set', this.setHeatingThresholdTemperature.bind(this))
        .on('get', this.getHeatingThresholdTemperature.bind(this))
        .setValue(this.checkTemperatureState(this.itemHeatingThresholdTemperature.state));

    otherService.getCharacteristic(this.homebridge.hap.Characteristic.TemperatureDisplayUnits)
        .on('get', this.getTemperatureDisplayUnits.bind(this))
        .setValue(this.temperatureDisplayUnits);

    return otherService;
};

//CurrentTemperature
ThermostatItem.prototype.updateCurrentTemperature = function(message) {
    this.otherService
        .getCharacteristic(this.homebridge.hap.Characteristic.CurrentTemperature)
        .setValue(this.checkTemperatureState(message));
};
ThermostatItem.prototype.getCurrentTemperatureState = function(callback) {
    var self = this;
    this.log("iOS - request current temperature state from " + this.itemCurrentTemperature.name + " (" + (self.name)+")");
    request(self.itemCurrentTemperature.link + '/state?type=json', function (error, response, body) {
        if (!error && response.statusCode == 200) {
            self.log("OpenHAB HTTP - response from " + self.itemCurrentTemperature.name + " (" + (self.name)+"): " + body);
            callback(undefined,self.checkTemperatureState(body));
        } else {
            self.log("OpenHAB HTTP - error from " + self.itemCurrentTemperature.name + " (" + (self.name)+"): " + error);
        }
    })
};

//CurrentHeatingCoolingState
ThermostatItem.prototype.getCurrentHeatingCoolingState = function(callback) {
    var self = this;
    this.log("iOS - request Current Heating/Cooling State state from " + this.itemTargetHeatingCoolingState.name + " (" + (self.name)+")");
    request(self.itemTargetHeatingCoolingState.link + '/state?type=json', function (error, response, body) {
        if (!error && response.statusCode == 200) {
            self.log("OpenHAB HTTP - response from " + self.itemTargetHeatingCoolingState.name + " (" + (self.name)+"): " + body);
            callback(undefined,self.checkCurrentHeatingCoolingState(body));
        } else {
            self.log("OpenHAB HTTP - error from " + self.itemTargetHeatingCoolingState.name + " (" + (self.name)+"): " + error);
        }
    })
};

//TargetHeatingCoolingState
ThermostatItem.prototype.updateTargetHeatingCoolingState = function(message) {
    this.otherService
        .getCharacteristic(this.homebridge.hap.Characteristic.TargtHeatingCoolingState)
        .setValue(this.checkTargetHeatingCoolingState(message));
    this.otherService
        .getCharacteristic(this.homebridge.hap.Characteristic.CurrentHeatingCoolingState)
        .setValue(this.checkCurrentHeatingCoolingState(message));
};
ThermostatItem.prototype.getTargetHeatingCoolingState = function(callback) {
    var self = this;
    this.log("iOS - request Target Heating/Cooling State from " + this.itemTargetHeatingCoolingState.name + " (" + (self.name)+")");
    request(self.itemTargetHeatingCoolingState.link + '/state?type=json', function (error, response, body) {
        if (!error && response.statusCode == 200) {
            self.log("OpenHAB HTTP - response from " + self.itemTargetHeatingCoolingState.name + " (" + (self.name)+"): " + body);
            callback(undefined,self.checkTargetHeatingCoolingState(body));
        } else {
            self.log("OpenHAB HTTP - error from " + self.itemTargetHeatingCoolingState.name + " (" + (self.name)+"): " + error);
        }
    })
};
ThermostatItem.prototype.setTargetHeatingCoolingState = function(value,callback) {
    callback();
};

//CoolingThresholdTemperature
ThermostatItem.prototype.updateCoolingThresholdTemperature = function(message) {
    this.otherService
        .getCharacteristic(this.homebridge.hap.Characteristic.CoolingThresholdTemperature)
        .setValue(this.checkTemperatureState(message));
};
ThermostatItem.prototype.getCoolingThresholdTemperature = function(callback) {
    var self = this;
    this.log("iOS - request Cooling Threshold Temperature state from " + this.itemCoolingThresholdTemperature.name + " (" + (self.name)+")");
    request(self.itemCoolingThresholdTemperature.link + '/state?type=json', function (error, response, body) {
        if (!error && response.statusCode == 200) {
            self.log("OpenHAB HTTP - response from " + self.itemCoolingThresholdTemperature.name + " (" + (self.name)+"): " + body);
            callback(undefined,self.checkTemperatureState(body));
        } else {
            self.log("OpenHAB HTTP - error from " + self.itemCoolingThresholdTemperature.name + " (" + (self.name)+"): " + error);
        }
    })
};
ThermostatItem.prototype.setCoolingThresholdTemperature = function(value,callback) {
    // var self = this;
    // //
    // // if (this.setInitialState) {
    // //     this.setInitialState = false;
    // //     callback();
    // //     return;
    // // }
    // //
    // // if (this.setFromOpenHAB) {
    // //     callback();
    // //     return;
    // // }
    //
    // this.log("iOS - send message to " + this.itemCoolingThresholdTemperature.name + ": " + value);
    // var command = value;
    // request.post(
    //     this.itemTargetDoorState.link,
    //     {
    //         body: command,
    //         headers: {'Content-Type': 'text/plain'}
    //     },
    //     function (error, response, body) {
    //         if (!error && response.statusCode == 201) {
    //             self.log("OpenHAB HTTP - response from " + self.itemCoolingThresholdTemperature.name + ": " + body);
    //         } else {
    //             self.log("OpenHAB HTTP - error from " + self.itemCoolingThresholdTemperature.name + ": " + error);
    //         }
    //         callback();
    //     }
    // );
    callback();
}

//HeatingThresholdTemperature
ThermostatItem.prototype.updateHeatingThresholdTemperature = function(message) {
    this.otherService
        .getCharacteristic(this.homebridge.hap.Characteristic.HeatingThresholdTemperature)
        .setValue(this.checkTemperatureState(message));
};
ThermostatItem.prototype.getHeatingThresholdTemperature = function(callback) {
    var self = this;
    this.log("iOS - request Heating Threshold Temperature state from " + this.itemHeatingThresholdTemperature.name + " (" + (self.name)+")");
    request(self.itemHeatingThresholdTemperature.link + '/state?type=json', function (error, response, body) {
        if (!error && response.statusCode == 200) {
            self.log("OpenHAB HTTP - response from " + self.itemHeatingThresholdTemperature.name + " (" + (self.name)+"): " + body);
            callback(undefined,self.checkTemperatureState(body));
        } else {
            self.log("OpenHAB HTTP - error from " + self.itemHeatingThresholdTemperature.name + " (" + (self.name)+"): " + error);
        }
    })
};
ThermostatItem.prototype.setHeatingThresholdTemperature = function(value, callback) {
    callback();
}

ThermostatItem.prototype.getTemperatureDisplayUnits = function(callback) {
    callback(undefined,this.temperatureDisplayUnits);
};

ThermostatItem.prototype.checkTemperatureState = function(state) {
    if ('Unitialized' === state){
        return 20.0;
    }
    return +state;
};

ThermostatItem.prototype.checkTargetHeatingCoolingState = function(state) {
    switch (state){
        case '0':
            return this.homebridge.hap.Characteristic.TargetHeatingCoolingState.OFF;
        case '1':
            return this.homebridge.hap.Characteristic.TargetHeatingCoolingState.HEAT;
        case '2':
            return this.homebridge.hap.Characteristic.TargetHeatingCoolingState.COOL;
        case '3':
            return this.homebridge.hap.Characteristic.TargetHeatingCoolingState.AUTO;
        default:
            return this.homebridge.hap.Characteristic.TargetHeatingCoolingState.OFF;
    }
};

ThermostatItem.prototype.checkCurrentHeatingCoolingState = function(state) {
    switch (state){
        case '0':
            return this.homebridge.hap.Characteristic.CurrentHeatingCoolingState.OFF;
        case '1':
            return this.homebridge.hap.Characteristic.CurrentHeatingCoolingState.HEAT;
        case '2':
            return this.homebridge.hap.Characteristic.CurrentHeatingCoolingState.COOL;
        case '3':
            return this.homebridge.hap.Characteristic.CurrentHeatingCoolingState.OFF;
        default:
            return this.homebridge.hap.Characteristic.CurrentHeatingCoolingState.OFF;
    }
};

/**
 * Export ThermostatItem
 * @type {ThermostatItem}
 */
module.exports = ThermostatItem;
<|endoftext|>


<commit_before>module.exports = function(grunt) {

	grunt.initConfig({

		meta: {
			banner: grunt.file.read('cookie.js').split('\n')[0]
		},

		lint: {
			all: ['grunt.js', 'cookie.js']
		},

		jshint: {
			options: {
				browser: true,
				evil: false,
				expr: true,
				supernew: true,
				eqeqeq: true,
				eqnull: true,
				forin: true,
				smarttabs: true
			}
		},

		mocha: {
			all: {
			    src: 'tests/index.html',
			    run: true
			}
		},

		min: {
			dist: {
				src: ['<banner>', 'cookie.js'],
				dest: 'cookie.min.js'
			}
		},

		watch: {
			files: ['cookie.js'],
			tasks: 'development'
		}

	});

	grunt.loadNpmTasks('grunt-mocha');

	grunt.registerTask('default', 'lint mocha min');
	grunt.registerTask('development', 'lint mocha');

};<commit_msg>add test alias for mocha<commit_after>module.exports = function(grunt) {

	grunt.initConfig({

		meta: {
			banner: grunt.file.read('cookie.js').split('\n')[0]
		},

		lint: {
			all: ['grunt.js', 'cookie.js']
		},

		jshint: {
			options: {
				browser: true,
				evil: false,
				expr: true,
				supernew: true,
				eqeqeq: true,
				eqnull: true,
				forin: true,
				smarttabs: true
			}
		},

		mocha: {
			all: {
			    src: 'tests/index.html',
			    run: true
			}
		},

		min: {
			dist: {
				src: ['<banner>', 'cookie.js'],
				dest: 'cookie.min.js'
			}
		},

		watch: {
			files: ['cookie.js'],
			tasks: 'development'
		}

	});

	grunt.loadNpmTasks('grunt-mocha');

	grunt.registerTask('default', 'lint mocha min');
	grunt.registerTask('development', 'lint mocha');
	grunt.registerTask('test', 'lmocha')

};<|endoftext|>


<commit_before>/*global module*/

module.exports = function (grunt) {
	'use strict';

	//<config:coffee.dist.dest>

	// grunt clean
	// grunt copy
	// grunt coffee
	// delete coffee files in build folder after compilation?

	grunt.initConfig({
		pkg: '<json:package.json>',

		meta: {
			banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
				'<%= grunt.template.today("yyyy-mm-dd") %> */'
		},

		watch: {
			files: './scripts/**/*.coffee',
			tasks: 'copy coffee'
		},

		// deletes the build folder
		clean: {
			build: {
				dest: './build/'
			}
		},

		// copy scripts to the build directory
		copy: {
			build: {
				src: './scripts/',
				dest: './build/'
			}
		},

		// compiles CoffeeScript to JavaScript
		coffee: {
			build: {
				src: './build/',
				dest: './build/',
				bare: true
			}
		},

		// concatenates files managed by RequireJS, sans minification
		requirejs: {
			build: {
				baseUrl: './build/',
				mainConfigFile: './build/main.js',
				name: 'main',
				out: './build/scripts.js',
				preserveLicenseComments: false,
				paths: {
					requireLib: 'libs/require'
				},
				include: ['requireLib'],
				findNestedDependencies: true,

				// let grunt's min handle this
				optimize: 'none'
			}
		},

		 // for some reason the minified file fails at runtime
		 // this is happening regardless of which minifier is used
		min: {
			build: {
				src: ['<banner>', './build/scripts.js'],
				dest: './build/scripts.min.js'
			}
		},

		lint: {
			build: ['./build/!(libs)**/*.js']
		},

		coffeeLint: {
			build: {
				src: './scripts/**/*.coffee',
				indentation: {
					value: 1
				},
				max_line_length: {
					level: 'ignore'
				},
				no_tabs: {
					level: 'ignore'
				}
			}
		},

		jshint: {
			options: {
				// CoffeeScript uses null for default parameter values
				eqnull: true
			}
		}
	});

	grunt.loadTasks('tasks');
	grunt.registerTask('bootstrap', 'clean copy coffee requirejs min');
	grunt.registerTask('dev', 'bootstrap watch');

	// deletes the js folder
	// compiles all coffee files
	// starts watching for coffee changes
	//grunt.registerTask('refresh', 'clean coffee watch');

	// starts watching for coffee changes
	//grunt.registerTask('default', 'coffee watch');
};<commit_msg>added coffeeLint task to bootstrap grunt task<commit_after>/*global module*/

module.exports = function (grunt) {
	'use strict';

	//<config:coffee.dist.dest>

	// grunt clean
	// grunt copy
	// grunt coffee
	// delete coffee files in build folder after compilation?

	grunt.initConfig({
		pkg: '<json:package.json>',

		meta: {
			banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
				'<%= grunt.template.today("yyyy-mm-dd") %> */'
		},

		watch: {
			files: './scripts/**/*.coffee',
			tasks: 'copy coffee'
		},

		// deletes the build folder
		clean: {
			build: {
				dest: './build/'
			}
		},

		// copy scripts to the build directory
		copy: {
			build: {
				src: './scripts/',
				dest: './build/'
			}
		},

		// compiles CoffeeScript to JavaScript
		coffee: {
			build: {
				src: './build/',
				dest: './build/',
				bare: true
			}
		},

		// concatenates files managed by RequireJS, sans minification
		requirejs: {
			build: {
				baseUrl: './build/',
				mainConfigFile: './build/main.js',
				name: 'main',
				out: './build/scripts.js',
				preserveLicenseComments: false,
				paths: {
					requireLib: 'libs/require'
				},
				include: ['requireLib'],
				findNestedDependencies: true,

				// let grunt's min handle this
				optimize: 'none'
			}
		},

		 // for some reason the minified file fails at runtime
		 // this is happening regardless of which minifier is used
		min: {
			build: {
				src: ['<banner>', './build/scripts.js'],
				dest: './build/scripts.min.js'
			}
		},

		lint: {
			build: ['./build/!(libs)**/*.js']
		},

		coffeeLint: {
			build: {
				src: './scripts/**/*.coffee',
				indentation: {
					value: 1
				},
				max_line_length: {
					level: 'ignore'
				},
				no_tabs: {
					level: 'ignore'
				}
			}
		},

		jshint: {
			options: {
				// CoffeeScript uses null for default parameter values
				eqnull: true
			}
		}
	});

	grunt.loadTasks('tasks');
	grunt.registerTask('bootstrap', 'coffeeLint clean copy coffee requirejs min');
	grunt.registerTask('dev', 'bootstrap watch');

	// deletes the js folder
	// compiles all coffee files
	// starts watching for coffee changes
	//grunt.registerTask('refresh', 'clean coffee watch');

	// starts watching for coffee changes
	//grunt.registerTask('default', 'coffee watch');
};<|endoftext|>


<commit_before>import Ember from 'ember';

import FdListformColumn from '../objects/fd-listform-column';
import FdViewAttributesProperty from '../objects/fd-view-attributes-property';
import FdAttributesTree from '../objects/fd-attributes-tree';
import FdViewAttributesMaster from '../objects/fd-view-attributes-master';
import FdViewAttributesDetail from '../objects/fd-view-attributes-detail';
import {
  getDataForBuildTree,
  getTreeNodeByNotUsedAttributes,
  getAssociationTreeNode,
  getTreeNodeByNotUsedAggregation,
  getClassTreeNode
 } from '../utils/fd-attributes-for-tree';
import { createPropertyName, restorationNodeTree, afterCloseNodeTree, findFreeNodeTreeNameIndex } from '../utils/fd-metods-for-tree';

export default Ember.Controller.extend({
  /**
    @private
    @property _showModalDialog
    @type Boolean
    @default false
  */
  _showModalDialog: false,

  /**
    Flag: indicates whether show tree.

    @private
    @property _showNotUsedAttributesTree
    @type Boolean
    @default false
  */
  _showNotUsedAttributesTree: false,

  /**
    Selected nodes in jsTree.

    @property selectedNodesNotUsedAttributesTree
    @type Array
    @default []
   */
  selectedNodesNotUsedAttributesTree: Ember.A(),

  /**
    Included plugins for jsTree.

    @property pluginsTree
    @type String
    @default 'wholerow, types'
   */
  pluginsTree: 'wholerow, types',

  /**
    Type settings for jsTree.

    @property typesOptionsTree
    @type Object
  */
  typesOptionsTree: Ember.computed(() => ({
    'property': {
      icon: 'assets/images/attribute.bmp'
    },
    'master': {
      icon: 'assets/images/master.bmp'
    },
    'detail': {
      icon: 'assets/images/datail.png'
    },
    'class': {
      icon: 'assets/images/class.bmp'
    }
  })),

  /**
    Data for jsTree.

    @property dataNotUsedAttributesTree
    @type Array
  */
  dataNotUsedAttributesTree: Ember.A(),

  /**
    Update data in tree.

    @method dataNotUsedAttributesTreeObserver
  */
  dataNotUsedAttributesTreeObserver: Ember.observer('_showNotUsedAttributesTree', function() {
    if (!this.get('_showNotUsedAttributesTree')) {
      return;
    }

    let dataobjectId = this.get('dataObject.id');
    let view = this.get('view');

    let dataForBuildTree = getDataForBuildTree(this.get('store'), dataobjectId);
    let attributesForTree = getTreeNodeByNotUsedAttributes(this.get('store'), dataForBuildTree.classes, view, 'type');
    let associationForTree = getAssociationTreeNode(Ember.A(), dataForBuildTree.associations, 'node_', dataobjectId, 'name');
    let aggregationForTree = getTreeNodeByNotUsedAggregation(dataForBuildTree.aggregations, view, 'name');

    let attributesTree = Ember.A();
    attributesTree.pushObjects([
      FdAttributesTree.create({
        text: this.get('i18n').t('forms.fd-editform-constructor.form-config-panel.tree.not-used-attributes.property'),
        type: 'class',
        id: 'attributes',
        children: attributesForTree,
        copyChildren: attributesForTree,
        state: { opened: true }
      }),
      FdAttributesTree.create({
        text: this.get('i18n').t('forms.fd-editform-constructor.form-config-panel.tree.not-used-attributes.master'),
        type: 'class',
        id: 'masters',
        children: associationForTree,
        copyChildren: associationForTree,
        state: { opened: true }
      }),
      FdAttributesTree.create({
        text: this.get('i18n').t('forms.fd-editform-constructor.form-config-panel.tree.not-used-attributes.detail'),
        type: 'class',
        id: 'details',
        children: aggregationForTree,
        copyChildren: aggregationForTree,
        state: { opened: true }
      })
    ]);

    this.set('dataNotUsedAttributesTree', attributesTree);
  }),

  /**
    @private
    @property _selectedIsFirst
    @readOnly
    @type Boolean
  */
  _selectedIsFirst: Ember.computed('selectedColumn', 'columns.[]', function() {
    return this.get('selectedColumn') === this.get('columns.firstObject');
  }).readOnly(),

  /**
    @private
    @property _selectedIsLast
    @readOnly
    @type Boolean
  */
  _selectedIsLast: Ember.computed('selectedColumn', 'columns.[]', function() {
    return this.get('selectedColumn') === this.get('columns.lastObject');
  }).readOnly(),

  queryParams: ['form', 'class'],

  formClass: Ember.computed.alias('model.listform'),

  view: Ember.computed.alias('model.view'),

  dataObject: Ember.computed.alias('model.dataobject'),

  /**
    The selected column.

    @property selectedColumn
    @type FdListformColumn
  */
  selectedColumn: undefined,

  /**
    Columns of the table in the list form.

    @property columns
    @type FdListformColumn[]
    @readOnly
  */
  columns: Ember.computed('view.definition', function() {
    let columns = Ember.A();
    let definition = this.get('view.definition');
    let length = definition.get('length');
    for (let i = 0; i < length; i++) {
      columns.pushObject(FdListformColumn.create({
        propertyDefinition: definition.objectAt(i),
      }));
    }

    return columns;
  }).readOnly(),

  actions: {
    /**
      Set the selected column.

      @method actions.selectColumn
      @param {FdListformColumn} column
    */
    selectColumn(column) {
      let selectedColumn = this.get('selectedColumn');
      let newSelectedColumn = selectedColumn === column ? undefined : column;
      this.set('selectedColumn', newSelectedColumn);

      if (!Ember.isNone(newSelectedColumn) && newSelectedColumn.get('propertyDefinition.name') === '') {
        this.set('_showNotUsedAttributesTree', true);
      } else {
        this.set('_showNotUsedAttributesTree', false);
      }
    },

    /**
      Adds a new column.

      @method actions.addColumn
    */
    addColumn() {
      let dataobject = this.get('dataObject');
      let attributes = dataobject.get('attributes');
      let atrIndex = findFreeNodeTreeNameIndex('newAttribute', 1, attributes, 'name');

      this.get('store').createRecord('fd-dev-attribute', {
        class: dataobject,
        name: 'newAttribute' + atrIndex,
        type: 'string',
        notNull: false,
        defaultValue: ''
      });

      let dataForBuildTree = getDataForBuildTree(this.get('store'), dataobject.get('id'));
      let newTree = getClassTreeNode(Ember.A(), dataForBuildTree.classes, dataobject.get('id'), 'type');
      this.set('model.attributes', newTree);

      let view = this.get('view');
      let viewDefinition = view.get('definition');
      let propertyDefinition = FdViewAttributesProperty.create({
        caption: `${this.get('i18n').t('forms.fd-listform-constructor.new-column-caption').toString()} #${this.incrementProperty('_newColumnIndex')}`,
        name: 'newAttribute' + atrIndex,
      });
      viewDefinition.pushObject(propertyDefinition);

      let column = FdListformColumn.create({
        propertyDefinition: propertyDefinition,
      });

      this.get('columns').pushObject(column);
      this.send('selectColumn', column);
      Ember.run.scheduleOnce('afterRender', this, this._scrollToSelected);
    },

    addEmptyControl() {
      let column = FdListformColumn.create({
        propertyDefinition: FdViewAttributesProperty.create({
          caption: `${this.get('i18n').t('forms.fd-listform-constructor.new-column-caption').toString()} #${this.incrementProperty('_newColumnIndex')}`,
          name: '',
        }),
      });

      this.get('columns').pushObject(column);
      this.send('selectColumn', column);
      Ember.run.scheduleOnce('afterRender', this, this._scrollToSelected);
    },

    /**
      Removes the selected column.

      @method actions.removeSelectedColumn
      @param {Boolean} approve The user is sure.
    */
    removeSelectedColumn(approve) {
      if (approve) {
        let columns = this.get('columns');
        let selectedColumn = this.get('selectedColumn');

        columns.removeObject(selectedColumn);
        this.set('selectedColumn', undefined);
      } else {
        this.set('_showModalDialog', true);
      }
    },

    /**
      Sorts the selected column.

      @method actions.sortSelectedColumn
      @param {Number} step Step of moving the column.
    */
    sortSelectedColumn(step) {
      let columns = this.get('columns');
      let selectedColumn = this.get('selectedColumn');
      let index = columns.indexOf(selectedColumn) + step;

      columns.removeObject(selectedColumn);
      columns.insertAt(index, selectedColumn);
    },

    save() {
      let view = Ember.A(this.get('view'));
      let viewDefinition = Ember.A();
      let columns = this.get('columns');
      for (let i = 0; i < columns.get('length'); i++) {
        let column = columns[i];
        viewDefinition.pushObject(column.get('propertyDefinition'));
      }

      view.set('definition', viewDefinition);

      let formName = this.get('formClass.name');
      if (this.get('formClass.isNew')) {
        this.set('formClass.caption', formName);
        this.set('formClass.stereotype', '«listform»');
        this.set('view.name', `${formName}ViewL`);
        this.set('formClass.formViews.firstObject.name', 'listview');
      }

      if (this.get('dataObject.isNew')) {
        this.set('dataObject.name', `${formName}Object`);
        this.set('dataObject.caption', `${formName}Object`);
      }

      let dataobject = this.get('dataObject');
      if (Ember.isNone(dataobject.get('caption'))) {
        dataobject.set('caption', dataobject.get('name'));
      }

      let formClass = this.get('formClass');
      if (Ember.isNone(formClass.get('caption'))) {
        formClass.set('caption', formClass.get('name'));
      }

      let attributes = dataobject.get('attributes');
      let changedAttributes = attributes.filterBy('hasDirtyAttributes');

      let association = this.get('store').peekAll('fd-dev-association');
      let changedAssociations = association.filterBy('hasDirtyAttributes');

      let aggregation = this.get('store').peekAll('fd-dev-aggregation');
      let changedAggregation = aggregation.filterBy('hasDirtyAttributes');

      dataobject.save().then(() => {
        this.get('view').save().then(() => {
          formClass.save().then(() => {
            this.get('formClass.formViews.firstObject').save().then(() => {
              this.set('class', undefined);
              this.set('form', this.get('formClass.id'));
            });
          });
          changedAttributes.map(a => a.save());
          changedAssociations.map(a => a.save());
          changedAggregation.map(a => a.save());
        });
      });
    },

    close() {
      this.transitionToRoute('fd-appstruct-form');
    },

    /**
      Set attribute in control.

      @method actions.setAttributeInControl
    */
    setAttributeInControl() {
      let selectedNodes = this.get('selectedNodesNotUsedAttributesTree')[0];
      let selectedColumn = this.get('selectedColumn');
      let treeData = this.get('dataNotUsedAttributesTree');

      // Create propertyName
      let propertyName = createPropertyName(selectedNodes, treeData[1], false);

      selectedColumn.set('type', selectedNodes.original.typeNode);
      let propertyDefinition;
      if (selectedNodes.type === 'detail') {
        propertyDefinition = FdViewAttributesDetail.create({
          caption: propertyName,
          name: propertyName,
          visible: true
        });

        selectedColumn.set('propertyDefinition', propertyDefinition);
      } else if (selectedNodes.type === 'master') {
        propertyDefinition = FdViewAttributesMaster.create({
          caption: propertyName,
          name: propertyName,
          visible: true
        });

        selectedColumn.set('propertyDefinition', propertyDefinition);
      } else {
        selectedColumn.set('propertyDefinition.caption', propertyName);
        selectedColumn.set('propertyDefinition.name', propertyName);
        propertyDefinition = selectedColumn.get('propertyDefinition');
      }

      let view = this.get('view');
      let viewDefinition = view.get('definition');
      viewDefinition.pushObject(propertyDefinition);

      this.set('_showNotUsedAttributesTree', false);
    },

    /**
      Don't set attribute in control.

      @method actions.deleteEmptyControl
    */
    deleteEmptyControl() {
      let columns = this.get('columns');
      let selectedColumn = this.get('selectedColumn');
      columns.removeObject(selectedColumn);
      this.set('selectedColumn', undefined);
      this.set('_showNotUsedAttributesTree', false);
    },

    /**
      Handles creating jsTree.

      @method actions.handleTreeDidBecomeReady
    */
    handleTreeDidBecomeReady() {
      let treeObject = this.get('treeObjectNotUsedAttributesTree');
      treeObject.on('open_node.jstree', this._openNodeTree.bind(this));
      treeObject.on('after_close.jstree', afterCloseNodeTree.bind(this));
    },
  },

  /**
    Scrolls the form to the selected control with jQuery.

    @private
    @method _scrollToSelected
  */
  _scrollToSelected() {
    let $verticalForm = Ember.$('.form.flexberry-vertical-form');
    let form = $verticalForm.children('.ui.segment');
    let scrollLeft = Ember.$('.positive:first').offset().left + form.scrollLeft() - (form.offset().left + 10);

    form.animate({ scrollLeft });
  },

  /**
    Overridden action for jsTree 'openNode'.

    @method _openNodeTree
  */
  _openNodeTree(e, data) {
    let treeData = this.get('dataNotUsedAttributesTree');
    restorationNodeTree(treeData, data.node.original, Ember.A(['master', 'class']), false, (function(node) {
      let view = this.get('view');
      let dataForBuildTree = getDataForBuildTree(this.get('store'), node.get('idNode'));
      let childrenAttributes = getTreeNodeByNotUsedAttributes(this.get('store'), dataForBuildTree.classes, view, 'type');
      let childrenNode = getAssociationTreeNode(childrenAttributes, dataForBuildTree.associations, node.get('id'), null, 'name');

      return childrenNode;
    }).bind(this));

    this.get('actionReceiverNotUsedAttributesTree').send('redraw');
  },
});
<commit_msg>Add willDestroy<commit_after>import Ember from 'ember';

import FdListformColumn from '../objects/fd-listform-column';
import FdViewAttributesProperty from '../objects/fd-view-attributes-property';
import FdAttributesTree from '../objects/fd-attributes-tree';
import FdViewAttributesMaster from '../objects/fd-view-attributes-master';
import FdViewAttributesDetail from '../objects/fd-view-attributes-detail';
import {
  getDataForBuildTree,
  getTreeNodeByNotUsedAttributes,
  getAssociationTreeNode,
  getTreeNodeByNotUsedAggregation,
  getClassTreeNode
 } from '../utils/fd-attributes-for-tree';
import { createPropertyName, restorationNodeTree, afterCloseNodeTree, findFreeNodeTreeNameIndex } from '../utils/fd-metods-for-tree';

export default Ember.Controller.extend({
  /**
    @private
    @property _showModalDialog
    @type Boolean
    @default false
  */
  _showModalDialog: false,

  /**
    Flag: indicates whether show tree.

    @private
    @property _showNotUsedAttributesTree
    @type Boolean
    @default false
  */
  _showNotUsedAttributesTree: false,

  /**
    Selected nodes in jsTree.

    @property selectedNodesNotUsedAttributesTree
    @type Array
    @default []
   */
  selectedNodesNotUsedAttributesTree: Ember.A(),

  /**
    Included plugins for jsTree.

    @property pluginsTree
    @type String
    @default 'wholerow, types'
   */
  pluginsTree: 'wholerow, types',

  /**
    Type settings for jsTree.

    @property typesOptionsTree
    @type Object
  */
  typesOptionsTree: Ember.computed(() => ({
    'property': {
      icon: 'assets/images/attribute.bmp'
    },
    'master': {
      icon: 'assets/images/master.bmp'
    },
    'detail': {
      icon: 'assets/images/datail.png'
    },
    'class': {
      icon: 'assets/images/class.bmp'
    }
  })),

  /**
    Data for jsTree.

    @property dataNotUsedAttributesTree
    @type Array
  */
  dataNotUsedAttributesTree: Ember.A(),

  /**
    Update data in tree.

    @method dataNotUsedAttributesTreeObserver
  */
  dataNotUsedAttributesTreeObserver: Ember.observer('_showNotUsedAttributesTree', function() {
    if (!this.get('_showNotUsedAttributesTree')) {
      return;
    }

    let dataobjectId = this.get('dataObject.id');
    let view = this.get('view');

    let dataForBuildTree = getDataForBuildTree(this.get('store'), dataobjectId);
    let attributesForTree = getTreeNodeByNotUsedAttributes(this.get('store'), dataForBuildTree.classes, view, 'type');
    let associationForTree = getAssociationTreeNode(Ember.A(), dataForBuildTree.associations, 'node_', dataobjectId, 'name');
    let aggregationForTree = getTreeNodeByNotUsedAggregation(dataForBuildTree.aggregations, view, 'name');

    let attributesTree = Ember.A();
    attributesTree.pushObjects([
      FdAttributesTree.create({
        text: this.get('i18n').t('forms.fd-editform-constructor.form-config-panel.tree.not-used-attributes.property'),
        type: 'class',
        id: 'attributes',
        children: attributesForTree,
        copyChildren: attributesForTree,
        state: { opened: true }
      }),
      FdAttributesTree.create({
        text: this.get('i18n').t('forms.fd-editform-constructor.form-config-panel.tree.not-used-attributes.master'),
        type: 'class',
        id: 'masters',
        children: associationForTree,
        copyChildren: associationForTree,
        state: { opened: true }
      }),
      FdAttributesTree.create({
        text: this.get('i18n').t('forms.fd-editform-constructor.form-config-panel.tree.not-used-attributes.detail'),
        type: 'class',
        id: 'details',
        children: aggregationForTree,
        copyChildren: aggregationForTree,
        state: { opened: true }
      })
    ]);

    this.set('dataNotUsedAttributesTree', attributesTree);
  }),

  /**
    @private
    @property _selectedIsFirst
    @readOnly
    @type Boolean
  */
  _selectedIsFirst: Ember.computed('selectedColumn', 'columns.[]', function() {
    return this.get('selectedColumn') === this.get('columns.firstObject');
  }).readOnly(),

  /**
    @private
    @property _selectedIsLast
    @readOnly
    @type Boolean
  */
  _selectedIsLast: Ember.computed('selectedColumn', 'columns.[]', function() {
    return this.get('selectedColumn') === this.get('columns.lastObject');
  }).readOnly(),

  queryParams: ['form', 'class'],

  formClass: Ember.computed.alias('model.listform'),

  view: Ember.computed.alias('model.view'),

  dataObject: Ember.computed.alias('model.dataobject'),

  /**
    The selected column.

    @property selectedColumn
    @type FdListformColumn
  */
  selectedColumn: undefined,

  /**
    Columns of the table in the list form.

    @property columns
    @type FdListformColumn[]
    @readOnly
  */
  columns: Ember.computed('view.definition', function() {
    let columns = Ember.A();
    let definition = this.get('view.definition');
    let length = definition.get('length');
    for (let i = 0; i < length; i++) {
      columns.pushObject(FdListformColumn.create({
        propertyDefinition: definition.objectAt(i),
      }));
    }

    return columns;
  }).readOnly(),

  actions: {
    /**
      Set the selected column.

      @method actions.selectColumn
      @param {FdListformColumn} column
    */
    selectColumn(column) {
      let selectedColumn = this.get('selectedColumn');
      let newSelectedColumn = selectedColumn === column ? undefined : column;
      this.set('selectedColumn', newSelectedColumn);

      if (!Ember.isNone(newSelectedColumn) && newSelectedColumn.get('propertyDefinition.name') === '') {
        this.set('_showNotUsedAttributesTree', true);
      } else {
        this.set('_showNotUsedAttributesTree', false);
      }
    },

    /**
      Adds a new column.

      @method actions.addColumn
    */
    addColumn() {
      let dataobject = this.get('dataObject');
      let attributes = dataobject.get('attributes');
      let atrIndex = findFreeNodeTreeNameIndex('newAttribute', 1, attributes, 'name');

      this.get('store').createRecord('fd-dev-attribute', {
        class: dataobject,
        name: 'newAttribute' + atrIndex,
        type: 'string',
        notNull: false,
        defaultValue: ''
      });

      let dataForBuildTree = getDataForBuildTree(this.get('store'), dataobject.get('id'));
      let newTree = getClassTreeNode(Ember.A(), dataForBuildTree.classes, dataobject.get('id'), 'type');
      this.set('model.attributes', newTree);

      let view = this.get('view');
      let viewDefinition = view.get('definition');
      let propertyDefinition = FdViewAttributesProperty.create({
        caption: `${this.get('i18n').t('forms.fd-listform-constructor.new-column-caption').toString()} #${this.incrementProperty('_newColumnIndex')}`,
        name: 'newAttribute' + atrIndex,
      });
      viewDefinition.pushObject(propertyDefinition);

      let column = FdListformColumn.create({
        propertyDefinition: propertyDefinition,
      });

      this.get('columns').pushObject(column);
      this.send('selectColumn', column);
      Ember.run.scheduleOnce('afterRender', this, this._scrollToSelected);
    },

    addEmptyControl() {
      let column = FdListformColumn.create({
        propertyDefinition: FdViewAttributesProperty.create({
          caption: `${this.get('i18n').t('forms.fd-listform-constructor.new-column-caption').toString()} #${this.incrementProperty('_newColumnIndex')}`,
          name: '',
        }),
      });

      this.get('columns').pushObject(column);
      this.send('selectColumn', column);
      Ember.run.scheduleOnce('afterRender', this, this._scrollToSelected);
    },

    /**
      Removes the selected column.

      @method actions.removeSelectedColumn
      @param {Boolean} approve The user is sure.
    */
    removeSelectedColumn(approve) {
      if (approve) {
        let columns = this.get('columns');
        let selectedColumn = this.get('selectedColumn');

        columns.removeObject(selectedColumn);
        this.set('selectedColumn', undefined);
      } else {
        this.set('_showModalDialog', true);
      }
    },

    /**
      Sorts the selected column.

      @method actions.sortSelectedColumn
      @param {Number} step Step of moving the column.
    */
    sortSelectedColumn(step) {
      let columns = this.get('columns');
      let selectedColumn = this.get('selectedColumn');
      let index = columns.indexOf(selectedColumn) + step;

      columns.removeObject(selectedColumn);
      columns.insertAt(index, selectedColumn);
    },

    save() {
      let view = Ember.A(this.get('view'));
      let viewDefinition = Ember.A();
      let columns = this.get('columns');
      for (let i = 0; i < columns.get('length'); i++) {
        let column = columns[i];
        viewDefinition.pushObject(column.get('propertyDefinition'));
      }

      view.set('definition', viewDefinition);

      let formName = this.get('formClass.name');
      if (this.get('formClass.isNew')) {
        this.set('formClass.caption', formName);
        this.set('formClass.stereotype', '«listform»');
        this.set('view.name', `${formName}ViewL`);
        this.set('formClass.formViews.firstObject.name', 'listview');
      }

      if (this.get('dataObject.isNew')) {
        this.set('dataObject.name', `${formName}Object`);
        this.set('dataObject.caption', `${formName}Object`);
      }

      let dataobject = this.get('dataObject');
      if (Ember.isNone(dataobject.get('caption'))) {
        dataobject.set('caption', dataobject.get('name'));
      }

      let formClass = this.get('formClass');
      if (Ember.isNone(formClass.get('caption'))) {
        formClass.set('caption', formClass.get('name'));
      }

      let attributes = dataobject.get('attributes');
      let changedAttributes = attributes.filterBy('hasDirtyAttributes');

      let association = this.get('store').peekAll('fd-dev-association');
      let changedAssociations = association.filterBy('hasDirtyAttributes');

      let aggregation = this.get('store').peekAll('fd-dev-aggregation');
      let changedAggregation = aggregation.filterBy('hasDirtyAttributes');

      dataobject.save().then(() => {
        this.get('view').save().then(() => {
          formClass.save().then(() => {
            this.get('formClass.formViews.firstObject').save().then(() => {
              this.set('class', undefined);
              this.set('form', this.get('formClass.id'));
            });
          });
          changedAttributes.map(a => a.save());
          changedAssociations.map(a => a.save());
          changedAggregation.map(a => a.save());
        });
      });
    },

    close() {
      this.transitionToRoute('fd-appstruct-form');
    },

    /**
      Set attribute in control.

      @method actions.setAttributeInControl
    */
    setAttributeInControl() {
      let selectedNodes = this.get('selectedNodesNotUsedAttributesTree')[0];
      let selectedColumn = this.get('selectedColumn');
      let treeData = this.get('dataNotUsedAttributesTree');

      // Create propertyName
      let propertyName = createPropertyName(selectedNodes, treeData[1], false);

      selectedColumn.set('type', selectedNodes.original.typeNode);
      let propertyDefinition;
      if (selectedNodes.type === 'detail') {
        propertyDefinition = FdViewAttributesDetail.create({
          caption: propertyName,
          name: propertyName,
          visible: true
        });

        selectedColumn.set('propertyDefinition', propertyDefinition);
      } else if (selectedNodes.type === 'master') {
        propertyDefinition = FdViewAttributesMaster.create({
          caption: propertyName,
          name: propertyName,
          visible: true
        });

        selectedColumn.set('propertyDefinition', propertyDefinition);
      } else {
        selectedColumn.set('propertyDefinition.caption', propertyName);
        selectedColumn.set('propertyDefinition.name', propertyName);
        propertyDefinition = selectedColumn.get('propertyDefinition');
      }

      let view = this.get('view');
      let viewDefinition = view.get('definition');
      viewDefinition.pushObject(propertyDefinition);

      this.set('_showNotUsedAttributesTree', false);
    },

    /**
      Don't set attribute in control.

      @method actions.deleteEmptyControl
    */
    deleteEmptyControl() {
      let columns = this.get('columns');
      let selectedColumn = this.get('selectedColumn');
      columns.removeObject(selectedColumn);
      this.set('selectedColumn', undefined);
      this.set('_showNotUsedAttributesTree', false);
    },

    /**
      Handles creating jsTree.

      @method actions.handleTreeDidBecomeReady
    */
    handleTreeDidBecomeReady() {
      let treeObject = this.get('treeObjectNotUsedAttributesTree');
      treeObject.on('open_node.jstree', this._openNodeTree.bind(this));
      treeObject.on('after_close.jstree', afterCloseNodeTree.bind(this));
    },
  },

  /**
    Scrolls the form to the selected control with jQuery.

    @private
    @method _scrollToSelected
  */
  _scrollToSelected() {
    let $verticalForm = Ember.$('.form.flexberry-vertical-form');
    let form = $verticalForm.children('.ui.segment');
    let scrollLeft = Ember.$('.positive:first').offset().left + form.scrollLeft() - (form.offset().left + 10);

    form.animate({ scrollLeft });
  },

  /**
    Overridden action for jsTree 'openNode'.

    @method _openNodeTree
  */
  _openNodeTree(e, data) {
    let treeData = this.get('dataNotUsedAttributesTree');
    restorationNodeTree(treeData, data.node.original, Ember.A(['master', 'class']), false, (function(node) {
      let view = this.get('view');
      let dataForBuildTree = getDataForBuildTree(this.get('store'), node.get('idNode'));
      let childrenAttributes = getTreeNodeByNotUsedAttributes(this.get('store'), dataForBuildTree.classes, view, 'type');
      let childrenNode = getAssociationTreeNode(childrenAttributes, dataForBuildTree.associations, node.get('id'), null, 'name');

      return childrenNode;
    }).bind(this));

    this.get('actionReceiverNotUsedAttributesTree').send('redraw');
  },

  /**
    Destroys helper.
  */
  willDestroy() {
    this._super(...arguments);
    let treeObject = this.get('treeObjectNotUsedAttributesTree');
    if (!Ember.isNone(treeObject)) {
      treeObject.off('open_node.jstree', this._openNodeTree.bind(this));
      treeObject.off('after_close.jstree', afterCloseNodeTree.bind(this));
    }
  }
});
<|endoftext|>