<commit_before>import $ from 'blingblingjs'
import hotkeys from 'hotkeys-js'

import * as Icons from './toolpallete.icons'
import {
  Selectable, Moveable, Padding, Margin, EditText, Font, Flex, Search,
  ColorPicker, BoxShadow, HueShift, MetaTip, Guides, Screenshot
} from '../features/'

import { provideSelectorEnginer } from '../features/search'

export default class ToolPallete extends HTMLElement {
  constructor() {
    super()

    this.toolbar_model = {
      g: { tool: 'guides', icon: Icons.ruler, label: 'Guides', description: 'Verify alignment' },
      i: { tool: 'inspector', icon: Icons.inspector, label: 'Inspect', description: 'Peak into the common & current styles of an element' },
      v: { tool: 'move', icon: Icons.move, label: 'Move', description: 'Push elements in, out & around' },
      // r: { tool: 'resize', icon: Icons.resize, label: 'Resize', description: '' },
      m: { tool: 'margin', icon: Icons.margin, label: 'Margin', description: 'Add or subtract outer space' },
      p: { tool: 'padding', icon: Icons.padding, label: 'Padding', description: 'Add or subtract inner space' },
      // b: { tool: 'border', icon: Icons.border, label: 'Border', description: '' },
      a: { tool: 'align', icon: Icons.align, label: 'Flexbox Align', description: 'Create or modify direction, distribution & alignment' },
      h: { tool: 'hueshift', icon: Icons.hueshift, label: 'Hue Shift', description: 'Change fg/bg hue, brightness, saturation & opacity' },
      d: { tool: 'boxshadow', icon: Icons.boxshadow, label: 'Shadow', description: 'Create & adjust position, blur & opacity of a box shadow' },
      // t: { tool: 'transform', icon: Icons.transform, label: '3D Transform', description: '' },
      f: { tool: 'font', icon: Icons.font, label: 'Font Styles', description: 'Change size, leading, kerning, & weight' },
      e: { tool: 'text', icon: Icons.type, label: 'Edit Text', description: 'Change any text on the page' },
      c: { tool: 'screenshot', icon: Icons.camera, label: 'Screenshot', description: 'Screenshot selected elements or the entire page' },
      s: { tool: 'search', icon: Icons.search, label: 'Search', description: 'Select elements by searching for them' },
    }

    this.$shadow = this.attachShadow({mode: 'open'})
    this.$shadow.innerHTML = this.render()

    this.selectorEngine = Selectable()
    this.colorPicker    = ColorPicker(this.$shadow, this.selectorEngine)
    provideSelectorEnginer(this.selectorEngine)
  }

  connectedCallback() {
    $('li[data-tool]', this.$shadow).on('click', e =>
      this.toolSelected(e.currentTarget) && e.stopPropagation())

    Object.entries(this.toolbar_model).forEach(([key, value]) =>
      hotkeys(key, e =>
        this.toolSelected(
          $(`[data-tool="${value.tool}"]`, this.$shadow)[0])))

    this.toolSelected($('[data-tool="guides"]', this.$shadow)[0])
  }

  disconnectedCallback() {
    this.deactivate_feature()
    this.selectorEngine.disconnect()
    hotkeys.unbind(
      Object.keys(this.toolbar_model).reduce((events, key) =>
        events += ',' + key, ''))
  }

  toolSelected(el) {
    if (typeof el === 'string')
      el = $(`[data-tool="${el}"]`, this.$shadow)[0]

    if (this.active_tool && this.active_tool.dataset.tool === el.dataset.tool) return

    if (this.active_tool) {
      this.active_tool.attr('data-active', null)
      this.deactivate_feature()
      this.selectorEngine.toggleOverlay(true)
    }

    el.attr('data-active', true)
    this.active_tool = el
    this[el.dataset.tool]()
  }

  render() {
    return `
      ${this.styles()}

        ${Object.entries(this.toolbar_model).reduce((list, [key, value]) => `
          ${list}

${value.icon}

        `,'')}

          <input type="color" value="">
          ${Icons.color_text}

          <input type="color" value="">
          ${Icons.color_background}

          <input type="color" value="">
          ${Icons.color_border}

    `
  }

  styles() {
    return `

    `
  }

  move() {
    this.deactivate_feature = Moveable('[data-selected=true]')
  }

  margin() {
    this.deactivate_feature = Margin('[data-selected=true]')
  }

  padding() {
    this.deactivate_feature = Padding('[data-selected=true]')
  }

  font() {
    this.deactivate_feature = Font('[data-selected=true]')
  }

  text() {
    this.selectorEngine.onSelectedUpdate(EditText)
    this.deactivate_feature = () =>
      this.selectorEngine.removeSelectedCallback(EditText)
  }

  align() {
    this.deactivate_feature = Flex('[data-selected=true]')
  }

  search() {
    this.deactivate_feature = Search($('[data-tool="search"]', this.$shadow))
  }

  boxshadow() {
    this.deactivate_feature = BoxShadow('[data-selected=true]')
  }

  hueshift() {
    this.deactivate_feature = HueShift('[data-selected=true]')
  }

  inspector() {
    this.deactivate_feature = MetaTip()
  }

  guides() {
    this.selectorEngine.toggleOverlay(false)
    this.deactivate_feature = Guides()
  }

  screenshot() {
    this.deactivate_feature = Screenshot()
  }

  activeTool() {
    return this.active_tool.dataset.tool
  }
}

customElements.define('tool-pallete', ToolPallete)<commit_msg>fixes color input not covering full icon area<commit_after>import $ from 'blingblingjs'
import hotkeys from 'hotkeys-js'

import * as Icons from './toolpallete.icons'
import {
  Selectable, Moveable, Padding, Margin, EditText, Font, Flex, Search,
  ColorPicker, BoxShadow, HueShift, MetaTip, Guides, Screenshot
} from '../features/'

import { provideSelectorEnginer } from '../features/search'

export default class ToolPallete extends HTMLElement {
  constructor() {
    super()

    this.toolbar_model = {
      g: { tool: 'guides', icon: Icons.ruler, label: 'Guides', description: 'Verify alignment' },
      i: { tool: 'inspector', icon: Icons.inspector, label: 'Inspect', description: 'Peak into the common & current styles of an element' },
      v: { tool: 'move', icon: Icons.move, label: 'Move', description: 'Push elements in, out & around' },
      // r: { tool: 'resize', icon: Icons.resize, label: 'Resize', description: '' },
      m: { tool: 'margin', icon: Icons.margin, label: 'Margin', description: 'Add or subtract outer space' },
      p: { tool: 'padding', icon: Icons.padding, label: 'Padding', description: 'Add or subtract inner space' },
      // b: { tool: 'border', icon: Icons.border, label: 'Border', description: '' },
      a: { tool: 'align', icon: Icons.align, label: 'Flexbox Align', description: 'Create or modify direction, distribution & alignment' },
      h: { tool: 'hueshift', icon: Icons.hueshift, label: 'Hue Shift', description: 'Change fg/bg hue, brightness, saturation & opacity' },
      d: { tool: 'boxshadow', icon: Icons.boxshadow, label: 'Shadow', description: 'Create & adjust position, blur & opacity of a box shadow' },
      // t: { tool: 'transform', icon: Icons.transform, label: '3D Transform', description: '' },
      f: { tool: 'font', icon: Icons.font, label: 'Font Styles', description: 'Change size, leading, kerning, & weight' },
      e: { tool: 'text', icon: Icons.type, label: 'Edit Text', description: 'Change any text on the page' },
      c: { tool: 'screenshot', icon: Icons.camera, label: 'Screenshot', description: 'Screenshot selected elements or the entire page' },
      s: { tool: 'search', icon: Icons.search, label: 'Search', description: 'Select elements by searching for them' },
    }

    this.$shadow = this.attachShadow({mode: 'open'})
    this.$shadow.innerHTML = this.render()

    this.selectorEngine = Selectable()
    this.colorPicker    = ColorPicker(this.$shadow, this.selectorEngine)
    provideSelectorEnginer(this.selectorEngine)
  }

  connectedCallback() {
    $('li[data-tool]', this.$shadow).on('click', e =>
      this.toolSelected(e.currentTarget) && e.stopPropagation())

    Object.entries(this.toolbar_model).forEach(([key, value]) =>
      hotkeys(key, e =>
        this.toolSelected(
          $(`[data-tool="${value.tool}"]`, this.$shadow)[0])))

    this.toolSelected($('[data-tool="guides"]', this.$shadow)[0])
  }

  disconnectedCallback() {
    this.deactivate_feature()
    this.selectorEngine.disconnect()
    hotkeys.unbind(
      Object.keys(this.toolbar_model).reduce((events, key) =>
        events += ',' + key, ''))
  }

  toolSelected(el) {
    if (typeof el === 'string')
      el = $(`[data-tool="${el}"]`, this.$shadow)[0]

    if (this.active_tool && this.active_tool.dataset.tool === el.dataset.tool) return

    if (this.active_tool) {
      this.active_tool.attr('data-active', null)
      this.deactivate_feature()
      this.selectorEngine.toggleOverlay(true)
    }

    el.attr('data-active', true)
    this.active_tool = el
    this[el.dataset.tool]()
  }

  render() {
    return `
      ${this.styles()}

        ${Object.entries(this.toolbar_model).reduce((list, [key, value]) => `
          ${list}

${value.icon}

        `,'')}

          <input type="color" value="">
          ${Icons.color_text}

          <input type="color" value="">
          ${Icons.color_background}

          <input type="color" value="">
          ${Icons.color_border}

    `
  }

  styles() {
    return `

    `
  }

  move() {
    this.deactivate_feature = Moveable('[data-selected=true]')
  }

  margin() {
    this.deactivate_feature = Margin('[data-selected=true]')
  }

  padding() {
    this.deactivate_feature = Padding('[data-selected=true]')
  }

  font() {
    this.deactivate_feature = Font('[data-selected=true]')
  }

  text() {
    this.selectorEngine.onSelectedUpdate(EditText)
    this.deactivate_feature = () =>
      this.selectorEngine.removeSelectedCallback(EditText)
  }

  align() {
    this.deactivate_feature = Flex('[data-selected=true]')
  }

  search() {
    this.deactivate_feature = Search($('[data-tool="search"]', this.$shadow))
  }

  boxshadow() {
    this.deactivate_feature = BoxShadow('[data-selected=true]')
  }

  hueshift() {
    this.deactivate_feature = HueShift('[data-selected=true]')
  }

  inspector() {
    this.deactivate_feature = MetaTip()
  }

  guides() {
    this.selectorEngine.toggleOverlay(false)
    this.deactivate_feature = Guides()
  }

  screenshot() {
    this.deactivate_feature = Screenshot()
  }

  activeTool() {
    return this.active_tool.dataset.tool
  }
}

customElements.define('tool-pallete', ToolPallete)<|endoftext|>


<commit_before>Seed({
		name : "Mold.Lib.Template",
		dna : "class",
		test : "Mold.Test.Lib.Template",
		include : [
			{ Builder : "Mold.Lib.VDom.Builder" },
			{ Ajax : "Mold.Lib.Ajax" },
			{ MultiLineString :  "Mold.Lib.MultiLineString" },
			{ Path : "Mold.Lib.Path" },
			{ Promise : "Mold.Lib.Promise" },
			{ Event : "Mold.Lib.Event" },
		]
	},
	function(markup, config){

		config = config || {};

		var ajax = new Ajax();
		var _tree = false;
		var _that = this;
		var _parseAsString= config.parseAsString || false;
		var undefined;

		Mold.mixin(this, new Event(this));

		//load the
		var _template = new Promise(function(resolve, reject){
			var data = markup;
			if(typeof markup === "function"){
				data = MultiLineString(markup)
				resolve(data);
				return;
			}

			if(Path.is(markup)){
				ajax
					.get(markup)
					.then(function(data){
						resolve(data);
					})
					.fail(function(error){
						reject(error);
					});
			}else{
				resolve(data);
			}
		});

		var _templateTree = new Promise(function(resolve, reject){
			_template.then(function(data){
				_tree = new Builder(data, this);
				resolve(_tree);
				_that.trigger("ready");
			})
		});

		/**
		 * @method  _connector
		 * @private
		 * @description collection of methods to bind a model to the template
		 * @type {Object}
		 */
		var _connector = {
			renderTimer : false,
			reRender : function(tree){
				clearTimeout(_connector.renderTimer);
				_connector.renderTimer = setTimeout(function(){
					if(!_parseAsString){
						tree.render();
					}else{
						tree.renderString();
					}
					_that.trigger("renderd", { tree : _tree });
				}, 2);

			},
			updateChildren : function(children, data, tree){
				if(Mold.isObject(children)){
					for(var childName in children){
						_connector.updateChild(children[childName], data[childName], tree, childName)
					}
				}else{
					throw new Error("only object implemented in _connector.updateChildren")
				}
			},
			updateChild : function(child, data, tree, name){
				//if blocknode
				if(child.type === 2){
					var blockData = {};
					blockData[name] = data;
					//console.log("set data", name, data)
					child.setData(blockData);
				}else{
					child.setData(data);
				}
				_connector.reRender(tree);

			},
			watchObjectProp : function(model, subTree, properties, path, tree, name){
				model.on(path + ".changed", function(e){
					switch(e.data.type){
						case "update":
						case "splice":
							//if subtree is an array update all childnodes
							if(Mold.isArray(subTree)){
								var i = 0, len = subTree.length;
								for(; i < len; i++){
									_connector.updateChild(subTree[i], e.data.object, tree, name);
									//if(e.data.type)
									_connect(model, subTree[i], properties, path, tree);
								}
							}else if(subTree.children && subTree.children[name]){
								_connector.updateChild(subTree, e.data.object, tree, name);
							}
							break;
						default:
							throw new Error("type " + e.data.type + " for watchObjectProp is not implemented!");
					}

				});
			},
			watchArray : function(model, subTree, properties, path, tree){
				model.on(path + ".changed", function(e){
					switch(e.data.type){
						case "update":
							if(Mold.isObject(e.data.object)){
								_connector.updateChildren(subTree, e.data.object, tree)
							}else{
								throw new Error("e.data.object is no Object, not Implemented");
							}
							break;
						default:
							throw new Error("method " + e.data.type + " for watchArray is not implemented!");
					}
				});
			},
			parseArray : function(model, subTree, properties, path, tree){
				var i = 0, len = subTree.children.length;
				for(; i < len; i++){
					var newPath = path + "." + i;
					//console.log("watch", newPath)

					_connector.watchArray(model, subTree.children[i], properties[0], newPath, tree)
					_connect(model, subTree.children[i], properties[0], newPath, tree)
				}
			},
			parseObject : function(model, subTree, properties, path, tree){
				for(var prop in properties){
					//_connector.watchObject
					var newPath = path + "." + prop;
					if(subTree.children){
						if(subTree.children[prop]){
							_connector.watchObjectProp(model, subTree.children[prop], properties[prop], newPath, tree, prop)
						}
					}else{
						_connector.watchObjectProp(model, subTree[prop], properties[prop], newPath, tree, prop)
						//throw new Error("subTree children is not defined, in _connector.parseObject!");
					}
				}
			}
		}

		var _connect = function(model, subTree, properties, path, tree){
			if(Mold.isArray(properties)){
				_connector.parseArray(model, subTree, properties, path, tree);
			}else if(Mold.isObject(properties)){
				_connector.parseObject(model, subTree, properties, path, tree);
			}
		}

		this.publics = {
			snatch : function(){

			},
			connect : function(model){
				_templateTree.then(function(tree){
					_connect(model, tree.dom, model.getProperties(), "data", tree);
					window.setTimeout(function(){
						model.triggerUpdate();
					}, 50)

				});
			},
			setData : function(data){
				_templateTree.then(function(tree){
					tree.dom.setData(data);
					if(!_parseAsString){
						tree.render();
					}else{
						tree.renderString();
					}
					_that.trigger("renderd", { tree : _tree });
				});
			},
			appendTo : function(element){
				_templateTree.then(function(tree){
					element.appendChild(tree.render())
					_that.trigger("renderd", { tree : _tree });
				})
			},
			getString : function(data){
				return new Promise(function(resolve, reject){
					_templateTree.then(function(tree){
						if(data){
							tree.dom.setData(data);
						}
						resolve(tree.renderString());
						_that.trigger("renderd", { tree : _tree });
					})
				});
			},
			get : _templateTree,
			tree : _templateTree
		}
	}
)<commit_msg>use setTimeout instead of window.setTimeout<commit_after>Seed({
		name : "Mold.Lib.Template",
		dna : "class",
		test : "Mold.Test.Lib.Template",
		include : [
			{ Builder : "Mold.Lib.VDom.Builder" },
			{ Ajax : "Mold.Lib.Ajax" },
			{ MultiLineString :  "Mold.Lib.MultiLineString" },
			{ Path : "Mold.Lib.Path" },
			{ Promise : "Mold.Lib.Promise" },
			{ Event : "Mold.Lib.Event" },
		]
	},
	function(markup, config){

		config = config || {};

		var ajax = new Ajax();
		var _tree = false;
		var _that = this;
		var _parseAsString= config.parseAsString || false;
		var undefined;

		Mold.mixin(this, new Event(this));

		//load the
		var _template = new Promise(function(resolve, reject){
			var data = markup;
			if(typeof markup === "function"){
				data = MultiLineString(markup)
				resolve(data);
				return;
			}

			if(Path.is(markup)){
				ajax
					.get(markup)
					.then(function(data){
						resolve(data);
					})
					.fail(function(error){
						reject(error);
					});
			}else{
				resolve(data);
			}
		});

		var _templateTree = new Promise(function(resolve, reject){
			_template.then(function(data){
				_tree = new Builder(data, this);
				resolve(_tree);
				_that.trigger("ready");
			})
		});

		/**
		 * @method  _connector
		 * @private
		 * @description collection of methods to bind a model to the template
		 * @type {Object}
		 */
		var _connector = {
			renderTimer : false,
			reRender : function(tree){
				clearTimeout(_connector.renderTimer);
				_connector.renderTimer = setTimeout(function(){
					if(!_parseAsString){
						tree.render();
					}else{
						tree.renderString();
					}
					_that.trigger("renderd", { tree : _tree });
				}, 2);

			},
			updateChildren : function(children, data, tree){
				if(Mold.isObject(children)){
					for(var childName in children){
						_connector.updateChild(children[childName], data[childName], tree, childName)
					}
				}else{
					throw new Error("only object implemented in _connector.updateChildren")
				}
			},
			updateChild : function(child, data, tree, name){
				//if blocknode
				if(child.type === 2){
					var blockData = {};
					blockData[name] = data;
					//console.log("set data", name, data)
					child.setData(blockData);
				}else{
					child.setData(data);
				}
				_connector.reRender(tree);

			},
			watchObjectProp : function(model, subTree, properties, path, tree, name){
				model.on(path + ".changed", function(e){
					switch(e.data.type){
						case "update":
						case "splice":
							//if subtree is an array update all childnodes
							if(Mold.isArray(subTree)){
								var i = 0, len = subTree.length;
								for(; i < len; i++){
									_connector.updateChild(subTree[i], e.data.object, tree, name);
									//if(e.data.type)
									_connect(model, subTree[i], properties, path, tree);
								}
							}else if(subTree.children && subTree.children[name]){
								_connector.updateChild(subTree, e.data.object, tree, name);
							}
							break;
						default:
							throw new Error("type " + e.data.type + " for watchObjectProp is not implemented!");
					}

				});
			},
			watchArray : function(model, subTree, properties, path, tree){
				model.on(path + ".changed", function(e){
					switch(e.data.type){
						case "update":
							if(Mold.isObject(e.data.object)){
								_connector.updateChildren(subTree, e.data.object, tree)
							}else{
								throw new Error("e.data.object is no Object, not Implemented");
							}
							break;
						default:
							throw new Error("method " + e.data.type + " for watchArray is not implemented!");
					}
				});
			},
			parseArray : function(model, subTree, properties, path, tree){
				var i = 0, len = subTree.children.length;
				for(; i < len; i++){
					var newPath = path + "." + i;
					//console.log("watch", newPath)

					_connector.watchArray(model, subTree.children[i], properties[0], newPath, tree)
					_connect(model, subTree.children[i], properties[0], newPath, tree)
				}
			},
			parseObject : function(model, subTree, properties, path, tree){
				for(var prop in properties){
					//_connector.watchObject
					var newPath = path + "." + prop;
					if(subTree.children){
						if(subTree.children[prop]){
							_connector.watchObjectProp(model, subTree.children[prop], properties[prop], newPath, tree, prop)
						}
					}else{
						_connector.watchObjectProp(model, subTree[prop], properties[prop], newPath, tree, prop)
						//throw new Error("subTree children is not defined, in _connector.parseObject!");
					}
				}
			}
		}

		var _connect = function(model, subTree, properties, path, tree){
			if(Mold.isArray(properties)){
				_connector.parseArray(model, subTree, properties, path, tree);
			}else if(Mold.isObject(properties)){
				_connector.parseObject(model, subTree, properties, path, tree);
			}
		}

		this.publics = {
			snatch : function(){

			},
			connect : function(model){
				_templateTree.then(function(tree){
					_connect(model, tree.dom, model.getProperties(), "data", tree);
					setTimeout(function(){
						model.triggerUpdate();
					}, 50)

				});
			},
			setData : function(data){
				_templateTree.then(function(tree){
					tree.dom.setData(data);
					if(!_parseAsString){
						tree.render();
					}else{
						tree.renderString();
					}
					_that.trigger("renderd", { tree : _tree });
				});
			},
			appendTo : function(element){
				_templateTree.then(function(tree){
					element.appendChild(tree.render())
					_that.trigger("renderd", { tree : _tree });
				})
			},
			getString : function(data){
				return new Promise(function(resolve, reject){
					_templateTree.then(function(tree){
						if(data){
							tree.dom.setData(data);
						}
						resolve(tree.renderString());
						_that.trigger("renderd", { tree : _tree });
					})
				});
			},
			get : _templateTree,
			tree : _templateTree
		}
	}
)<|endoftext|>


<commit_before>define(['text!./notifications.html','app','lodash','utilities/km-user-notification-service',
        'utilities/km-utilities','filters/moment','ionsound'], function(template,app,_) {
    app.directive('userNotifications', function() {
        return {
            restrict: 'EAC',
            replace: true,
            template: template,
            controller: ['$scope', '$rootScope', 'IUserNotificationService', '$timeout', '$filter','authentication',
                function($scope, $rootScope, userNotificationService, $timeout, $filter, authentication) {

                    var pageNumber = 0;
                    var pageLength = 10;

                    //============================================================
                    //
                    //
                    //============================================================
                    $scope.timePassed = function(createdOn) {
                        return $filter("fromNow")(createdOn);
                    }
    	           var notificationTimer;
                    //============================================================
                    //
                    //
                    //============================================================
                    getNotification = function() {
                        if ($rootScope.user && $rootScope.user.isAuthenticated) {
                            // if (canQuery) {
                            var queryMyNotifications;
                            // canQuery = false;
                            queryMyNotifications = {$or:[{'state': 'read'},{'state': 'unread'}]};
                            if ($scope.notifications) {
                                var notification = _.first($scope.notifications);
                                if (notification)
                                    queryMyNotifications = {
                                        $and: [{
                                            "createdOn": {
                                                "$gt": new Date(notification.createdOn).toISOString()
                                            },
                                            $or:[{'state': 'read'},{'state': 'unread'}]
                                        }]
                                    };
                            }

                            userNotificationService.query(queryMyNotifications, pageNumber, pageLength)
                                .then(function(data) {
                                    if (!data || data.length === 0)
                                        return;
                                    var localNotifications;
                                    if ($scope.notifications) {
                                        localNotifications = _.clone($scope.notifications);
                                        _.each(data, function(message) {
                                            localNotifications.push(message);
                                        });

                                        if(ion)
                                            ion.sound.play("bell_ring");
                                    } else {
                                        localNotifications = data;
                                    }
                                    $scope.notifications = [];
                                    $scope.notifications = $filter("orderBy")(localNotifications, 'createdOn', true);
                                })
                                .catch(function(error){
                                    if(error.data.statusCode==401){
                                        authentication.getUser();
                                    }
                                })
                                .finally(function() {
                                   notificationTimer =  $timeout(function() { getNotification();}, 10000);
                                });
                            //}
                        }

                    };
                    //============================================================
                    //
                    //
                    //============================================================
                    $scope.updateStatus = function(notification,status, $event) {
                        userNotificationService.update(notification.id, {
                                'state': status
                            })
                            .then(function() {
                                notification.state = status;
                            });
                            if($event)
                                $event.stopPropagation();
                    };

                    //============================================================
                    //
                    //
                    //============================================================
                    $scope.isUnread = function(notification) {

                        return notification && notification.state == 'unread';
                    };

                    $scope.$on('$destroy', function(evt){
                        $timeout.cancel(notificationTimer);
                    });

//                    $scope.$on('signIn', function(evt,user){
//                        $timeout(function(){
//                            console.log('notification after signin')
//                            getNotification();
//                            },5000);
//                    });
    	           $scope.$on('signOut', function(evt,user){
                       $timeout.cancel(notificationTimer);
                    });

                    getNotification();

                    $rootScope.$watch('user', function(newVla,oldVal){
                        if(newVla && newVla!=oldVal){
                            $timeout.cancel(notificationTimer);
                            getNotification();
                        }
                    });

                    $scope.getURL = function(notification){

                        if(notification.type=='documentNotification')
                            return '/management/requests/' + notification.data.workflowId + '/publishRecord';
                        else
                            return '#';//'/mailbox/' + notification.id;
                    }

                    ion.sound({
                        sounds: [
                            {
                                name: "bell_ring"
                            }
                        ],
                        volume: 0.5,
                        path: "/app/libs/ionsound/sounds/",
                        preload: true
                    });
                }
            ]

        };
    });
});
<commit_msg>stop notification when server returns 401<commit_after>define(['text!./notifications.html','app','lodash','utilities/km-user-notification-service',
        'utilities/km-utilities','filters/moment','ionsound'], function(template,app,_) {
    app.directive('userNotifications', function() {
        return {
            restrict: 'EAC',
            replace: true,
            template: template,
            controller: ['$scope', '$rootScope', 'IUserNotificationService', '$timeout', '$filter','authentication',
                function($scope, $rootScope, userNotificationService, $timeout, $filter, authentication) {

                    var pageNumber = 0;
                    var pageLength = 10;

                    //============================================================
                    //
                    //
                    //============================================================
                    $scope.timePassed = function(createdOn) {
                        return $filter("fromNow")(createdOn);
                    }
    	           var notificationTimer;
                    //============================================================
                    //
                    //
                    //============================================================
                    getNotification = function() {
                        if ($rootScope.user && $rootScope.user.isAuthenticated) {
                            // if (canQuery) {
                            var queryMyNotifications;
                            // canQuery = false;
                            queryMyNotifications = {$or:[{'state': 'read'},{'state': 'unread'}]};
                            if ($scope.notifications) {
                                var notification = _.first($scope.notifications);
                                if (notification)
                                    queryMyNotifications = {
                                        $and: [{
                                            "createdOn": {
                                                "$gt": new Date(notification.createdOn).toISOString()
                                            },
                                            $or:[{'state': 'read'},{'state': 'unread'}]
                                        }]
                                    };
                            }
    	                    var continueNotification = true;
                            userNotificationService.query(queryMyNotifications, pageNumber, pageLength)
                                .then(function(data) {
                                    if (!data || data.length === 0)
                                        return;
                                    var localNotifications;
                                    if ($scope.notifications) {
                                        localNotifications = _.clone($scope.notifications);
                                        _.each(data, function(message) {
                                            localNotifications.push(message);
                                        });

                                        if(ion)
                                            ion.sound.play("bell_ring");
                                    } else {
                                        localNotifications = data;
                                    }
                                    $scope.notifications = [];
                                    $scope.notifications = $filter("orderBy")(localNotifications, 'createdOn', true);
                                })
                                .catch(function(error){
                                    if(error.data.statusCode==401){
                                        continueNotification = false;
                                    }
                                })
                                .finally(function() {
                                   if(continueNotification)
                                        notificationTimer =  $timeout(function() { getNotification();}, 10000);
                                });
                            //}
                        }

                    };
                    //============================================================
                    //
                    //
                    //============================================================
                    $scope.updateStatus = function(notification,status, $event) {
                        userNotificationService.update(notification.id, {
                                'state': status
                            })
                            .then(function() {
                                notification.state = status;
                            });
                            if($event)
                                $event.stopPropagation();
                    };

                    //============================================================
                    //
                    //
                    //============================================================
                    $scope.isUnread = function(notification) {

                        return notification && notification.state == 'unread';
                    };

                    $scope.$on('$destroy', function(evt){
                        $timeout.cancel(notificationTimer);
                    });

//                    $scope.$on('signIn', function(evt,user){
//                        $timeout(function(){
//                            console.log('notification after signin')
//                            getNotification();
//                            },5000);
//                    });
    	           $scope.$on('signOut', function(evt,user){
                       $timeout.cancel(notificationTimer);
                    });

                    getNotification();

                    $rootScope.$watch('user', function(newVla,oldVal){
                        if(newVla && newVla!=oldVal){
                            $timeout.cancel(notificationTimer);
                            getNotification();
                        }
                    });

                    $scope.getURL = function(notification){

                        if(notification.type=='documentNotification')
                            return '/management/requests/' + notification.data.workflowId + '/publishRecord';
                        else
                            return '#';//'/mailbox/' + notification.id;
                    }

                    ion.sound({
                        sounds: [
                            {
                                name: "bell_ring"
                            }
                        ],
                        volume: 0.5,
                        path: "/app/libs/ionsound/sounds/",
                        preload: true
                    });
                }
            ]

        };
    });
});
<|endoftext|>


<commit_before>import AbstractPagedController from 'hospitalrun/controllers/abstract-paged-controller';
export default AbstractPagedController.extend();<commit_msg>Moved sort properties to proper location<commit_after>import AbstractPagedController from 'hospitalrun/controllers/abstract-paged-controller';
export default AbstractPagedController.extend({
    sortProperties: ['dateFulfilled'],
    // Sort in descending order
    sortAscending: false,

});<|endoftext|>


<commit_before>//'use strict';

smgContainer.controller('MatchController',
		function ($scope, $route, $routeParams, $rootScope, $cookies, $sce, $window,
		          $location, MatchService, GetGameInfoService, GetPlayerInfoService) {

            $scope.gameInfo = {};
            $scope.playerIds;

            var state = {};
            var lastState = state;
			var matchInfo = {};
			var lastMovePlayerId;
			var operations;
			var playersInfo = [];

			/*
			 * Method used to get all the information for the game,
			 * and create the changeApi channel to get the match information frequently.
			 */
			var getGameInfo = function () {
				GetGameInfoService.get({gameId: $routeParams.gameId}).
						$promise.then(function (data) {
							if (data['error'] == 'WRONG_GAME_ID') {
								alert('Sorry, Wrong Game ID provided!');
							} else {
								console.log("GetGameService from server: " + data);
								// 1. Change the onMessage method on socket.
								$rootScope.socket.onmessage = function (event) {
									console.log(event.data);
									var originalData = event.data;
									var jsonData = JSON.stringify(eval("(" + originalData + ')'));
									var data = angular.fromJson(jsonData);
									var channelApiPushState = data['gameState'];
									getMatchInfo();
									sendUpdateUIToGame(channelApiPushState);
								}
								// 2. Get game information.
								$scope.gameInfo.url = sceTrustedUrl(data['url']);
								$scope.gameInfo.height = data['height'];
								$scope.gameInfo.width = data['width'];
								$scope.gameInfo.gameName = data['gameName'];
								$scope.gameInfo.pics = data['pics'];
							}
						}
				);
			}

			/*
			 Method using "GET" method to get all the match information
			 */
			var getMatchInfo = function () {
				MatchService.get({matchId: $routeParams.matchId,
					accessSignature: $cookies.accessSignature, playerId: $cookies.playerId}).
						$promise.then(function (data) {
							if (data['error'] == "WRONG_ACCESS_SIGNATURE") {
								alert('Sorry, Wrong AccessSignature received!');
							} else if (data['error'] == 'WRONG_PLAYER_ID') {
								alert('Sorry, Wrong Player ID received!');
							} else if (data['error'] == 'JSON_PARSE_ERROR') {
								alert('Sorry, Wrong JSON string format received!');
							} else {
								//console.log("Get Match Info : " + data);
								// 1. Get all the match information into the matchInfo variable.

                                matchInfo.playerIds = data['playerIds'];
                                $scope.playerIds = angular.fromJson(matchInfo.playerIds);
								console.log("First time playerIds get " + $scope.playerIds);
								console.log("typeOf PlayerThatHasTurn : " + (typeof data['playerThatHasTurn']) + ", and it's " + data['playerThatHasTurn']);
								matchInfo.playerThatHasTurn = data['playerThatHasTurn'];
								matchInfo.gameOverScores = data['gameOverScores'];
								matchInfo.gameOverReason = data['gameOverReason'];
								matchInfo.history = data['history'];

								// 2. Set certain information to $scope.

								for(var i = 0; i < $scope.playerIds.length; i++) {
									$scope.playerIds[i] = $scope.playerIds[i].toString();
								};

								lastMovePlayerId = matchInfo.playerThatHasTurn;
								matchInfo.playerThatHasTurn = matchInfo.playerThatHasTurn;
							}
						}
				);
			}

			/**
			 * Method used to send converted moves to server.
			 */
			var sendMoveToServer = function (operations) {
				if (operations.length == 1 && operations[0]['type'] == 'GameReady') {
					// If we get "GameReady" operation, no need to send it to the server.
					return;
				}
				// 1. make up a move.
				var move = {
					"accessSignature": $cookies.accessSignature,
					"playerIds": $scope.playerIds,
					"operations": operations
				};
				var jsonMove = angular.toJson(move);
				// 2. send jsonfied data to server.
				MatchService.save({matchId: $routeParams.matchId}, jsonMove).
						$promise.then(function (data) {
							if (data['error'] == "WRONG_ACCESS_SIGNATURE") {
								alert('Sorry, Wrong Access Signature received!');
							} else if (data['error'] == 'WRONG_PLAYER_ID') {
								alert('Sorry, Wrong Player ID received!');
							} else if (data['error'] == "JSON_PARSE_ERROR") {
								alert('Sorry, Wrong JSON Format received!');
							} else if (data['error'] == "MISSING_INFO") {
								alert('Sorry, Incompleted JSON data received!');
							} else {
								var sentMoveReceivedData = data['gameState'];
								console.log("In the container, it receives the data from server " + sentMoveReceivedData);
								sendUpdateUIToGame(sentMoveReceivedData);
							}
						}
				);
			}

			/**
			 * Helper function used to get sce trusted url
			 */
			var sceTrustedUrl = function (url) {
				return $sce.trustAsResourceUrl(url);
			}

			/**
			 * Method used to end current game in two situation:
			 * 1. Game has a winner.
			 * 2. One of the players surrenders.
			 */
			$scope.endGame = function () {
				$cookies.socket.close();
				$location.url('/');
			}

			/**
			 * Method used to get all the players' information.
			 * @param playerIds
			 */
			var getAllPlayersInfo = function (allPlayerIds) {
				for (playerId in allPlayerIds) {
					GetPlayerInfoService.get({playerId: $cookies.playerId,
						targetId: playerId, accessSignature: $cookies.accessSignature}).
							$promise.then(function (data) {
							//	console.log(data);
								if (data['error'] == 'WRONG_ACCESS_SIGNATURE') {
									alert('Sorry, Wrong Access Signature provided!');
								} else if (data['error'] == 'WRONG_TARGETID') {
									alert('Sorry, Wrong Target ID provided!');
								} else {
									playersInfo.push(data);
								}
							}
					);
				}
			}

			/*
			 parameter: message should be : UpdateUI, VerifyMove
			 */
			$scope.sendMessageToIframe = function (message) {
				var win = $window.document.getElementById('iframe1').contentWindow;
				win.postMessage(message, "*");
				//console.log('toIframe');
			};

			function listener(event) {
				var data = event.data;
				console.log("In the container, it receives the data from the game Iframe " + data['type']);
				/*
				 check whether the data is GameReady(), if it is, send updateUI() to the game.
				 format of GameReady: {"type":"GameReady"}
				 */
				if (data['type'] === "GameReady") {
					replyGameReady();
				} else if (data['type'] === "MakeMove") {
					//get operations
					operations = data['operations'];
					console.log("In the container, it sends to the server, operations are " + operations);
					sendMoveToServer(operations);
				} else if (data['type'] === "VerifyMoveDone") {
					//deal with verifyMoveDone
					//no hacker detected
				} else {
					console.log("In the container listener, can't deal with the message from the game!!")
				}

				if (angular.isUndefined($scope.debug)) {
					$scope.debug = "Received: " + JSON.stringify(data);
				} else {
					$scope.operations = data;
					$scope.debug += "Received: " + JSON.stringify(data);
				}
				$scope.$apply();
			};

			function replyGameReady() {
				/*
				 The initial updateUI() has this given format
				 [
				 {'yourPlayerId' : $cookies.playerId},
				 {'playersInfo' : [{'playerId' : playerId1},{'playerId' : playerId2}]},   //if your playerId == id1, you should send the initial move
				 {'state' : []},
				 {'lastState' : []},
				 {'lastMove' : []},
				 {'lastMovePlayerId' : ''},
				 {'playerIdToNumberOfTokensInPot' : ''}
				 ]
				 */

				var hardCodeInitialUpdateUI = {
					'type': 'UpdateUI',
					'yourPlayerId': '42',
					'playersInfo': [
						{'playerId': '42'},
						{'playerId': '43'}
					],
					'state': {},
					'lastState': null,
					'lastMove': [],
					'lastMovePlayerId': null,
					'playerIdToNumberOfTokensInPot': {}
				};

				var initialUpdateUI = {
					'type': 'UpdateUI',
					'yourPlayerId': $cookies.playerId,
					'playersInfo': [
						{'playerId': $scope.playerIds[0]},
						{'playerId': $scope.playerIds[1]}
					],
					'state': {},
					'lastState': null,
					'lastMove': [],
					'lastMovePlayerId': null,
					'playerIdToNumberOfTokensInPot': {}
				};
				console.log("in the container, it sends the initial UpdateUI is " + angular.toJson(initialUpdateUI));
				$scope.sendMessageToIframe(initialUpdateUI);
			}

			function sendVerifyMoveToGame(newState) {
				lastState = state;
				state = newState;
				var verifyMove = {
					"type": "VerifyMove",
					'playersInfo': [
						{'playerId': $scope.playerIds[0]},
						{'playerId': $scope.playerIds[1]}
					],
					'state': newState,
					'lastState': state,
					'lastMove': null,
					"lastMovePlayerId": lastMovePlayerId,
					"playerIdToNumberOfTokensInPot": {}
				};
				$scope.sendMessageToIframe(verifyMove);
			};

			function sendUpdateUIToGame(newState) {
				var hardCodeUpdateUI = {
					"type": "UpdateUI",
					'yourPlayerId': 42,
					'playersInfo': [
						{'playerId': '42'},
						{'playerId': '43'}
					],
					'state': {},
					'lastState': null,
					'lastMove': [],
					'lastMovePlayerId': null,
					'playerIdToNumberOfTokensInPot': {}
				};
				lastState = state;
				state = newState;
				var updateUI = {
					"type": "UpdateUI",
					'yourPlayerId': $cookies.playerId,
					'playersInfo': [
						{'playerId': $scope.playerIds[0]},
						{'playerId': $scope.playerIds[1]}
					],
					'state': state,
					'lastState': {},
					'lastMove': [],
					"lastMovePlayerId": $cookies.playerId.toString(),
					//"lastMovePlayerId": lastMovePlayerId.toString(),
					"playerIdToNumberOfTokensInPot": {}
				};
				console.log("sendUpdateUIToGame" + updateUI.toString());
				console.log(angular.toJson(updateUI));
				console.log(lastMovePlayerId);
				$scope.sendMessageToIframe(updateUI);
			}

			// Formal program starts here.
			if (!$cookies.accessSignature || !$cookies.playerId) {
				alert('You have to log in first!');
				$location.url('/');
			} else {
				if ($window.addEventListener) {
					addEventListener("message", listener, false);
				} else {
					attachEvent("onmessage", listener);
				}
				// 1. Get game information.
				getGameInfo();
				// 2. Get match information.
				getMatchInfo();
				// 3. get players information.
				getAllPlayersInfo($scope.playerIds);
			}
		}

);<commit_msg>clarify the console.log statement<commit_after>//'use strict';

smgContainer.controller('MatchController',
		function ($scope, $route, $routeParams, $rootScope, $cookies, $sce, $window,
		          $location, MatchService, GetGameInfoService, GetPlayerInfoService) {

            $scope.gameInfo = {};
            $scope.playerIds;

            var state = {};
            var lastState = state;
			var matchInfo = {};
			var lastMovePlayerId;
			var operations;
			var playersInfo = [];

			/*
			 * Method used to get all the information for the game,
			 * and create the changeApi channel to get the match information frequently.
			 */
			var getGameInfo = function () {
				GetGameInfoService.get({gameId: $routeParams.gameId}).
						$promise.then(function (data) {
							if (data['error'] == 'WRONG_GAME_ID') {
								alert('Sorry, Wrong Game ID provided!');
							} else {
								console.log("GetGameService from server: " + angular.toJson(data));
								// 1. Change the onMessage method on socket.
								$rootScope.socket.onmessage = function (event) {
									var originalData = event.data;
									var jsonData = JSON.stringify(eval("(" + originalData + ')'));
                                    var data = angular.fromJson(jsonData);
                                    console.log("In the Channel, in the onMessage method " + angular.toJson(data));
                                    var channelApiPushState = data['gameState'];
									//getMatchInfo();
                                    console.log("The APIState passed to send method is " + angular.toJson(channelApiPushState));
									sendUpdateUIToGame(channelApiPushState);
								};
								// 2. Get game information.
								$scope.gameInfo.url = sceTrustedUrl(data['url']);
								$scope.gameInfo.height = data['height'];
								$scope.gameInfo.width = data['width'];
								$scope.gameInfo.gameName = data['gameName'];
								$scope.gameInfo.pics = data['pics'];
							}
						}
				);
			};

			/*
			 Method using "GET" method to get all the match information
			 */
			var getMatchInfo = function () {
				MatchService.get({matchId: $routeParams.matchId,
					accessSignature: $cookies.accessSignature, playerId: $cookies.playerId}).
						$promise.then(function (data) {
							if (data['error'] == "WRONG_ACCESS_SIGNATURE") {
								alert('Sorry, Wrong AccessSignature received!');
							} else if (data['error'] == 'WRONG_PLAYER_ID') {
								alert('Sorry, Wrong Player ID received!');
							} else if (data['error'] == 'JSON_PARSE_ERROR') {
								alert('Sorry, Wrong JSON string format received!');
							} else {
								console.log("Get Match Info : " + angular.toJson(data));
								// 1. Get all the match information into the matchInfo variable.

                                matchInfo.playerIds = data['playerIds'];
                                $scope.playerIds = angular.fromJson(matchInfo.playerIds);
								console.log("First time playerIds get " + $scope.playerIds);
								console.log("typeOf PlayerThatHasTurn : " + (typeof data['playerThatHasTurn']) + ", and it's " + data['playerThatHasTurn']);
								matchInfo.playerThatHasTurn = data['playerThatHasTurn'];
								matchInfo.gameOverScores = data['gameOverScores'];
								matchInfo.gameOverReason = data['gameOverReason'];
								matchInfo.history = data['history'];

								// 2. Set certain information to $scope.

								for(var i = 0; i < $scope.playerIds.length; i++) {
									$scope.playerIds[i] = $scope.playerIds[i].toString();
								}

								lastMovePlayerId = matchInfo.playerThatHasTurn;
								matchInfo.playerThatHasTurn = matchInfo.playerThatHasTurn;
							}
						}
				);
			};

			/**
			 * Method used to send converted moves to server.
			 */
			var sendMoveToServer = function (operations) {
				if (operations.length == 1 && operations[0]['type'] == 'GameReady') {
					// If we get "GameReady" operation, no need to send it to the server.
					return;
				}
				// 1. make up a move.
				var move = {
					"accessSignature": $cookies.accessSignature,
					"playerIds": $scope.playerIds,
					"operations": operations
				};
				var jsonMove = angular.toJson(move);
				// 2. send jsonfied data to server.
				MatchService.save({matchId: $routeParams.matchId}, jsonMove).
						$promise.then(function (data) {
							if (data['error'] == "WRONG_ACCESS_SIGNATURE") {
								alert('Sorry, Wrong Access Signature received!');
							} else if (data['error'] == 'WRONG_PLAYER_ID') {
								alert('Sorry, Wrong Player ID received!');
							} else if (data['error'] == "JSON_PARSE_ERROR") {
								alert('Sorry, Wrong JSON Format received!');
							} else if (data['error'] == "MISSING_INFO") {
								alert('Sorry, Incompleted JSON data received!');
							} else {
								var sentMoveReceivedData = data['gameState'];//not the same with API
								console.log("In the container, the player who sent the operations receives from server " + angular.toJson(sentMoveReceivedData));
								sendUpdateUIToGame(sentMoveReceivedData);
							}
						}
				);
			};

			/**
			 * Helper function used to get sce trusted url
			 */
			var sceTrustedUrl = function (url) {
				return $sce.trustAsResourceUrl(url);
			};

			/**
			 * Method used to end current game in two situation:
			 * 1. Game has a winner.
			 * 2. One of the players surrenders.
			 */
			$scope.endGame = function () {
				$cookies.socket.close();
				$location.url('/');
			};

			/**
			 * Method used to get all the players' information.
			 * @param playerIds
			 */
			var getAllPlayersInfo = function (allPlayerIds) {
				for (playerId in allPlayerIds) {
					GetPlayerInfoService.get({playerId: $cookies.playerId,
						targetId: playerId, accessSignature: $cookies.accessSignature}).
							$promise.then(function (data) {
							//	console.log(data);
								if (data['error'] == 'WRONG_ACCESS_SIGNATURE') {
									alert('Sorry, Wrong Access Signature provided!');
								} else if (data['error'] == 'WRONG_TARGETID') {
									alert('Sorry, Wrong Target ID provided!');
								} else {
									playersInfo.push(data);
								}
							}
					);
				}
			};

			/*
			 parameter: message should be : UpdateUI, VerifyMove
			 */
			$scope.sendMessageToIframe = function (message) {
				var win = $window.document.getElementById('iframe1').contentWindow;
				win.postMessage(message, "*");
			};

			function listener(event) {
				var data = event.data;
				console.log("In the container, it receives the data from the game Iframe " + data['type']);
				/*
				 check whether the data is GameReady(), if it is, send updateUI to the game.
				 format of GameReady: {"type":"GameReady"}
				 */
				if (data['type'] === "GameReady") {
					replyGameReady();
				} else if (data['type'] === "MakeMove") {
					//get operations
					operations = data['operations'];
					console.log("In the container, it sends to the server, operations are " + angular.toJson(operations));
					sendMoveToServer(operations);
				} else if (data['type'] === "VerifyMoveDone") {
					//deal with verifyMoveDone
					//no hacker detected
				} else {
					console.log("In the container listener, can't deal with the message from the game!!");
                    console.log("It is " + data['type']);
				}

				if (angular.isUndefined($scope.debug)) {
					$scope.debug = "Received: " + JSON.stringify(data);
				} else {
					$scope.operations = data;
					$scope.debug += "Received: " + JSON.stringify(data);
				}
				$scope.$apply();
			}

			function replyGameReady() {

				var initialUpdateUI = {
					'type': 'UpdateUI',
					'yourPlayerId': $cookies.playerId,
					'playersInfo': [
						{'playerId': $scope.playerIds[0]},
						{'playerId': $scope.playerIds[1]}
					],
					'state': {},
					'lastState': null,
					'lastMove': [],
					'lastMovePlayerId': null,
					'playerIdToNumberOfTokensInPot': {}
				};
				console.log("in the container, it sends the initial UpdateUI is " + angular.toJson(initialUpdateUI));
				$scope.sendMessageToIframe(initialUpdateUI);
			}

			function sendVerifyMoveToGame(newState) {
				lastState = state;
				state = newState;
				var verifyMove = {
					"type": "VerifyMove",
					'playersInfo': [
						{'playerId': $scope.playerIds[0]},
						{'playerId': $scope.playerIds[1]}
					],
					'state': newState,
					'lastState': state,
					'lastMove': null,
					"lastMovePlayerId": lastMovePlayerId,
					"playerIdToNumberOfTokensInPot": {}
				};
				$scope.sendMessageToIframe(verifyMove);
			}

			function sendUpdateUIToGame(newState) {

				lastState = state;
				state = newState;
				var updateUI = {
					"type": "UpdateUI",
					'yourPlayerId': $cookies.playerId,
					'playersInfo': [
						{'playerId': $scope.playerIds[0]},
						{'playerId': $scope.playerIds[1]}
					],
					'state': state,
					'lastState': lastState,
					'lastMove': [],
					"lastMovePlayerId": $cookies.playerId.toString(),
					"playerIdToNumberOfTokensInPot": {}
				};
				console.log("In the container, it sends the following UpdateUI to the game: " + angular.toJson(updateUI));
				$scope.sendMessageToIframe(updateUI);
			}

			// Formal program starts here.
			if (!$cookies.accessSignature || !$cookies.playerId) {
				alert('You have to log in first!');
				$location.url('/');
			} else {
				if ($window.addEventListener) {
					addEventListener("message", listener, false);
				} else {
					attachEvent("onmessage", listener);
				}
				// 1. Get game information.
				getGameInfo();
				// 2. Get match information.
				getMatchInfo();
				// 3. get players information.
				getAllPlayersInfo($scope.playerIds);
			}
		}

);<|endoftext|>


<commit_before>var annotationApp = angular.module('annotationApp');

annotationApp.controller('TextController', function($scope) {
});
<commit_msg>Don't redefine the app in TextController<commit_after>annotationApp.controller('TextController', function($scope) {
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import loadAll from 'ember-osf/utils/load-relationship';
import permissions from 'ember-osf/const/permissions';
import fixSpecialChar from 'ember-osf/utils/fix-special-char';

/**
 * @module ember-preprints
 * @submodule mixins
 */

/**
 * The submit controller/template is used to handle both Add and Edit modes for a preprint.  Contains
 * the setupController items necessary for both Add and Edit Modes.
 *
 * @class SetupSubmitControllerMixin
 */

export default Ember.Mixin.create({
    theme: Ember.inject.service(),
    panelActions: Ember.inject.service('panelActions'),

    setupSubmitController(controller, model) {
        //setupController method that will be run for both Add and Edit modes for submit form.
        if (controller.get('model.isLoaded'))
            controller.clearFields();
        controller.set('editMode', this.get('editMode'));

        // Fetch values required to operate the page: user and userNodes
        let userNodes = Ember.A();

        this.get('store').findAll('preprint-provider')
            .then((providers) => {
                controller.set('providers', providers);
            }
        );
        this.get('theme.provider').then(provider => {
            provider.query('licensesAcceptable', {'page[size]': 20}).then(licenses => {
                controller.set('availableLicenses', licenses);
            });
        });
        this.get('currentUser').load()
            .then((user) => {
                controller.set('user', user);
                return user;
            }).then((user) => loadAll(user, 'nodes', userNodes, {
                'filter[preprint]': false
            }).then(() => {
                // TODO Hack: API does not support filtering current_user_permissions in the way we desire, so filter
                // on front end for now until filtering support can be added to backend
                let onlyAdminNodes = userNodes.filter((item) => item.get('currentUserPermissions').includes(permissions.ADMIN));
                controller.set('userNodes', onlyAdminNodes);
                controller.set('userNodesLoaded', true);
            }));

        // If editMode, these initial fields are set to pre-populate form with preprint/node data.
        if (this.get('editMode')) {
            this.loadEditModeDefaults(controller, model, this.get('node'));
        }

    },
    // This function helps prepopulate all the preprint fields in Edit mode.
    loadEditModeDefaults(controller, model, node) {
        controller.set('filePickerState', 'existing'); // In edit mode, dealing with existing project
        controller.set('existingState', 'new'); // In edit mode, only option to change file is to upload a NEW file
        controller.set('node', node);
        controller.set('nodeTitle', fixSpecialChar(node.get('title')));
        controller.set('nodeLocked', true);
        controller.set('titleValid', true);
        model.get('primaryFile').then((file) => {
            controller.set('selectedFile', file);
        });
        this.get('panelActions').close('Upload');
        this.get('panelActions').open('Submit');
    }
});
<commit_msg>Remove unnecessary usage of fixspecialchar<commit_after>import Ember from 'ember';
import loadAll from 'ember-osf/utils/load-relationship';
import permissions from 'ember-osf/const/permissions';

/**
 * @module ember-preprints
 * @submodule mixins
 */

/**
 * The submit controller/template is used to handle both Add and Edit modes for a preprint.  Contains
 * the setupController items necessary for both Add and Edit Modes.
 *
 * @class SetupSubmitControllerMixin
 */

export default Ember.Mixin.create({
    theme: Ember.inject.service(),
    panelActions: Ember.inject.service('panelActions'),

    setupSubmitController(controller, model) {
        //setupController method that will be run for both Add and Edit modes for submit form.
        if (controller.get('model.isLoaded'))
            controller.clearFields();
        controller.set('editMode', this.get('editMode'));

        // Fetch values required to operate the page: user and userNodes
        let userNodes = Ember.A();

        this.get('store').findAll('preprint-provider')
            .then((providers) => {
                controller.set('providers', providers);
            }
        );
        this.get('theme.provider').then(provider => {
            provider.query('licensesAcceptable', {'page[size]': 20}).then(licenses => {
                controller.set('availableLicenses', licenses);
            });
        });
        this.get('currentUser').load()
            .then((user) => {
                controller.set('user', user);
                return user;
            }).then((user) => loadAll(user, 'nodes', userNodes, {
                'filter[preprint]': false
            }).then(() => {
                // TODO Hack: API does not support filtering current_user_permissions in the way we desire, so filter
                // on front end for now until filtering support can be added to backend
                let onlyAdminNodes = userNodes.filter((item) => item.get('currentUserPermissions').includes(permissions.ADMIN));
                controller.set('userNodes', onlyAdminNodes);
                controller.set('userNodesLoaded', true);
            }));

        // If editMode, these initial fields are set to pre-populate form with preprint/node data.
        if (this.get('editMode')) {
            this.loadEditModeDefaults(controller, model, this.get('node'));
        }

    },
    // This function helps prepopulate all the preprint fields in Edit mode.
    loadEditModeDefaults(controller, model, node) {
        controller.set('filePickerState', 'existing'); // In edit mode, dealing with existing project
        controller.set('existingState', 'new'); // In edit mode, only option to change file is to upload a NEW file
        controller.set('node', node);
        controller.set('nodeTitle', node.get('title'));
        controller.set('nodeLocked', true);
        controller.set('titleValid', true);
        model.get('primaryFile').then((file) => {
            controller.set('selectedFile', file);
        });
        this.get('panelActions').close('Upload');
        this.get('panelActions').open('Submit');
    }
});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    Image,
    View,
    ScrollView
} from 'react-native';

import {
  Card
} from 'react-native-elements'

import Constants from '../config/constants';
import Player from '../models/player';

const GET_CURRENT_PLAYER_STATS_URI = Constants.BASE_URL + 'current_user/stats';

class StatsScreen extends Component {

  constructor(props) {
    super(props);
    this.state = {
      playerStats: {},
    };
  }

  componentDidMount() {
    this.fetchData();
  }

  render() {
      return (
          <ScrollView>
            <View style={styles.container}>
              <View style={styles.imageContainer}>
                <Image source={this.state.pic} style={styles.theimage} />
              </View>
              <Card style={styles.contentview}>
                  <View style={styles.item}>
                    <Text style={styles.text}>Position</Text>
                    <Text style={styles.text}>{this.state.playerStats.ranking}</Text>
                  </View>
                  <View style={styles.item}>
                    <Text style={styles.text}>Win ratio</Text>
                    <Text style={styles.text}>{this.state.playerStats.winRatio}</Text>
                  </View>
                  <View style={styles.item}>
                    <Text style={styles.text}>Wins</Text>
                    <Text style={styles.text}>{this.state.playerStats.wins}</Text>
                  </View>
                  <View style={styles.item}>
                    <Text style={styles.text}>Fails</Text>
                    <Text style={styles.text}>{this.state.playerStats.losses}</Text>
                  </View>
                  <View style={styles.item}>
                    <Text style={styles.text}>Goals for</Text>
                    <Text style={styles.text}>{this.state.playerStats.goalsFor}</Text>
                  </View>
                  <View style={styles.item}>
                    <Text style={styles.text}>Goals against</Text>
                    <Text style={styles.text}>{this.state.playerStats.goalsAgainst}</Text>
                  </View>
                  <View style={styles.item}>
                    <Text style={styles.text}>Goals diff</Text>
                    <Text style={styles.text}>{this.state.playerStats.goalsDiff}</Text>
                  </View>
              </Card>
            </View>
          </ScrollView>
      );
  }

  fetchData() {
    var headers = new Headers();
    headers.append("Authorization", "Token token=" + Constants.API_TOKEN);

    fetch(GET_CURRENT_PLAYER_STATS_URI, {
      headers: headers,
    })
      .then((response) => response.json())
      .then((responseData) => {

        console.log(responseData);
        var player = new Player(responseData.user);
        this.setState({
          playerStats: responseData,
          player: player,
          pic: {
            uri: player.getPlayerImageUrl()
          }
        });
      })
      .done();
  }
}

export default StatsScreen;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 60
  },
  imageContainer: {
    marginTop: 40,
    marginBottom: 40,
    alignItems: 'center',
    justifyContent: 'center'
  },
  theimage: {
    flex: 0,
    width: 80,
    height: 80,
    borderRadius: 40
  },
  contentview: {
    flexDirection: 'column',
    flex: 1,
    width: '100%',
    paddingLeft: '10%',
    paddingRight: '10%'
  },
  item: {
    flexDirection: 'row',
    marginBottom: 20
  },
  text: {
    flex: 1,
    fontSize: 20
  }

});
<commit_msg>statsscreen<commit_after>import React, { Component } from 'react';
import {
    StyleSheet,
    Text,
    Image,
    View,
    ScrollView
} from 'react-native';

import {
  Card
} from 'react-native-elements'

import Constants from '../config/constants';
import Colors from '../config/colors';
import Player from '../models/player';

const GET_CURRENT_PLAYER_STATS_URI = Constants.BASE_URL + 'current_user/stats';

class StatsScreen extends Component {

  constructor(props) {
    super(props);
    this.state = {
      playerStats: {},
    };
  }

  componentDidMount() {
    this.fetchData();
  }

  render() {
      return (
          <ScrollView style={styles.container}>
            <View>
              <View style={styles.imageContainer}>
                <Image source={this.state.pic} style={styles.theimage} />
              </View>
              <Card style={styles.contentview}>
                  <View style={styles.item}>
                    <Text style={styles.text}>Position</Text>
                    <Text style={styles.text}>{this.state.playerStats.ranking}</Text>
                  </View>
                  <View style={styles.item}>
                    <Text style={styles.text}>Win ratio</Text>
                    <Text style={styles.text}>{this.state.playerStats.winRatio}</Text>
                  </View>
                  <View style={styles.item}>
                    <Text style={styles.text}>Wins</Text>
                    <Text style={styles.text}>{this.state.playerStats.wins}</Text>
                  </View>
                  <View style={styles.item}>
                    <Text style={styles.text}>Fails</Text>
                    <Text style={styles.text}>{this.state.playerStats.losses}</Text>
                  </View>
                  <View style={styles.item}>
                    <Text style={styles.text}>Goals for</Text>
                    <Text style={styles.text}>{this.state.playerStats.goalsFor}</Text>
                  </View>
                  <View style={styles.item}>
                    <Text style={styles.text}>Goals against</Text>
                    <Text style={styles.text}>{this.state.playerStats.goalsAgainst}</Text>
                  </View>
                  <View style={styles.item}>
                    <Text style={styles.text}>Goals diff</Text>
                    <Text style={styles.text}>{this.state.playerStats.goalsDiff}</Text>
                  </View>
              </Card>
            </View>
          </ScrollView>
      );
  }

  fetchData() {
    var headers = new Headers();
    headers.append("Authorization", "Token token=" + Constants.API_TOKEN);

    fetch(GET_CURRENT_PLAYER_STATS_URI, {
      headers: headers,
    })
      .then((response) => response.json())
      .then((responseData) => {

        console.log(responseData);
        var player = new Player(responseData.user);
        this.setState({
          playerStats: responseData,
          player: player,
          pic: {
            uri: player.getPlayerImageUrl()
          }
        });
      })
      .done();
  }
}

export default StatsScreen;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.grey6
  },
  imageContainer: {
    marginTop: 100,
    marginBottom: 40,
    alignItems: 'center',
    justifyContent: 'center'
  },
  theimage: {
    flex: 0,
    width: 80,
    height: 80,
    borderRadius: 40
  },
  contentview: {
    flexDirection: 'column',
    flex: 1,
    width: '100%',
    paddingLeft: '10%',
    paddingRight: '10%'
  },
  item: {
    flexDirection: 'row',
    marginBottom: 20
  },
  text: {
    flex: 1,
    fontSize: 20
  }

});
<|endoftext|>


<commit_before>//cells.js
'use strict';
/* jshint indent: false */

angular
		.module('celllogger')

		.controller(
				'CellloggerCtrl',
				function($scope, $http, leafletData, $filter, AlertService,
						MAPSERVER, MAXS2LEVEL, leafletEvents, WEBSERVICE,
						$interval) {

					$scope.desaturate = true;
					$scope.controller = 'CellloggerCtrl';
					$scope.search = {
						range : 365,
						serving : "all",
						network : "all"
					};
					$scope.providers = [];
					$scope.s2zoom = MAPSERVER.center.zoom;
					$scope.mouseclass = null;

					function getProviders() {
						$http
								.get(WEBSERVICE + '/measurementproviders', {})
								.error(function(err) {
									console.log(err);
								})
								.success(
										function(result) {
											// console.log(result);
											angular
													.forEach(
														result.providers.buckets,
														function(provider) {
//															$scope.providers
//																	.push({
//																		name : provider.key,
//																		mccmnc : provider.key
//																	});
															$http
																	.get( WEBSERVICE + '/provider',{ params:{ _id:provider.key}})
																	.error(	function(err) {
																		console.log(err);
																	})
																	.success(function(result) {
																			if (result.hits.total == "1"){
																			$scope.providers.push({
																				name : result.hits.hits[0]._source.name,
																				mccmnc : provider.key

																			});
																			} else {
																				$scope.providers.push({
																					name : provider.key,
																					mccmnc : provider.key

																				});
																			}
																		})

														})
											// result.forEach(function(provider){
											// $scope.providers.push({name:provider.name,mccmnc:{mcc:provider.mcc,mnc:provider.mnc}});
											// })

										})
					}
					getProviders();

					$scope.dateOptions = {
						formatYear : 'yy',
						startingDay : 1
					};

					$scope.formats = [ 'dd-MM-yyyy', 'yyyy/MM/dd',
							'dd.MM.yyyy', 'shortDate' ];
					$scope.format = $scope.formats[0];

					function getGeoHashes() {
						$http.defaults.useXDomain = true;

						if ($scope.bounds) {
							$scope.mouseclass = "wait";
							var gp = 6;
							switch (true) {
							case ($scope.s2zoom < 5):
								gp = 2;
								break;
							case ($scope.s2zoom > 4 && $scope.s2zoom < 7):
								gp = 3;
								break;
							case ($scope.s2zoom > 6 && $scope.s2zoom < 9):
								gp = 4;
								break;
							case ($scope.s2zoom > 8 && $scope.s2zoom < 12):
								gp = 5;
								break;
							case ($scope.s2zoom > 11 && $scope.s2zoom < 14):
								gp = 6;
								break;
							case ($scope.s2zoom > 14):
								gp = 7;
								break;
							}

							var params = {
								datePrecision : 730,
								geohashPrecision : (gp),
								bottom_left : [ $scope.bounds.southWest.lat,
										$scope.bounds.southWest.lng ],
								top_right : [ $scope.bounds.northEast.lat,
										$scope.bounds.northEast.lng ]
							};

							if ($scope.search.mccmnc) {
								params.net = $scope.search.mccmnc.split('-')[1];
								params.mcc = $scope.search.mccmnc.split('-')[0];
							}
							if ($scope.search.dt) {
								params.timestamp = new Date($scope.search.dt)
										.getTime();
							}
							if ($scope.search.range) {
								params.datePrecision = $scope.search.range;
							}
							if ($scope.search.serving !== 'all')
								params.serving = $scope.search.serving === "true"
							if ($scope.search.network !== 'all')
								params.radio = $scope.search.network

							$http.get(WEBSERVICE + '/measurementcellcount', {
								params : params
							}).error(function(err) {
								console.log(err);
							}).success(function(result) {

								$scope.distinctcount = result.cells.value;

							})

							$http
									.get(WEBSERVICE + '/coverage', {
										params : params
									})
									.error(function(err) {
										console.log(err);
									})
									.success(
											function(result) {

												$scope.measurementcount = result.hits.total;

												var maxValue = result.aggregations.cellgrid.buckets[0].doc_count;

												var colorFunction = new L.HSLHueFunction(
														new L.Point(1, 120),
														new L.Point(maxValue, 0),
														{
															outputSaturation : '100%',
															outputLuminosity : '50%'
														});
												var fillColorFunction = new L.HSLHueFunction(
														new L.Point(1, 120),
														new L.Point(maxValue, 0),
														{
															outputSaturation : '100%',
															outputLuminosity : '50%'
														});
												function geoHashOptions() {
													var options = {
														recordsField : 'buckets',
														geohashField : 'key',
														displayOptions : {
															doc_count : {
																color : colorFunction,
																fillColor : fillColorFunction,
																gradient : false
															}
														},
														layerOptions : {
															fillOpacity : 0.5,
															opacity : 1,
															weight : 1,
															gradient : true
														}
													};
													return options;
												}

												angular
														.extend(
																$scope,
																{
																	geohash : {
																		data : result.aggregations.cellgrid,
																		options : geoHashOptions()
																	}
																})
											})
							$scope.mouseclass = null;
						}
					}

					// function getTotalinScope(){
					// var gp=6;
					// switch(true){
					// case ($scope.s2zoom<5):
					// gp=2;
					// break;
					// case ($scope.s2zoom>4 && $scope.s2zoom<7):
					// gp=3;
					// break;
					// case ($scope.s2zoom>6 && $scope.s2zoom<9):
					// gp=4;
					// break;
					// case ($scope.s2zoom>8 && $scope.s2zoom<12):
					// gp=5;
					// break;
					// case ($scope.s2zoom>11&& $scope.s2zoom<14):
					// gp=6;
					// break;
					// case ($scope.s2zoom>14):
					// gp=7;
					// break;
					// }

					// var params={
					// datePrecision:365,
					// geohashPrecision:(gp),
					// bottom_left:[$scope.bounds.southWest.lat,$scope.bounds.southWest.lng],
					// top_right:[$scope.bounds.northEast.lat,$scope.bounds.northEast.lng]
					// };

					// if($scope.search.mccmnc){
					// params.net=$scope.search.mccmnc.mnc;
					// params.mcc=$scope.search.mccmnc.mcc;
					// }
					// if($scope.search.dt){
					// params.timestamp=new Date($scope.search.dt).getTime();
					// }
					// if($scope.search.serving!=='all')
					// params.serving=$scope.search.serving==="true"
					// if($scope.search.network!=='all')
					// params.radio=$scope.search.network
					// console.log(params);
					// $http.get(WEBSERVICE + '/measurementcellcount',{
					// params: params
					// })
					// .error(function(err){
					// console.log(err);
					// })
					// .success(function(result){
					// console.log(result);
					// $scope.distinctcount=result.cells.value;

					// })
					// }

					function getTotal() {
						var params = {
							datePrecision : 7000
						}

						$http.get(WEBSERVICE + '/measurementcount', {
							params : params
						}).error(function(err) {
							console.log(err);
						}).success(function(result) {
							$scope.total = result.total;
						})
					}

					getTotal();
					getGeoHashes();

					// Regular updates
					$scope.stopUpdate = function() {
						if (angular.isDefined(stop)) {
							$interval.cancel(stop);
							stop = undefined;
						}
					}

					var stop = $interval(function() {
						getTotal();
						// getTotalinScope();
					}, 3000);

					$scope.$on("$destroy", function() {
						$scope.stopUpdate();
					});

					$scope.$watch('search', function(value) {
						getGeoHashes();
					})

					$scope.refresh = function() {
						getGeoHashes();
					}

					$scope.today = function() {
						$scope.dt = new Date();
					};
					$scope.today();

					$scope.clear = function() {
						$scope.search.dt = null;
					};

					// Disable weekend selection
					$scope.disabled = function(date, mode) {
						return (mode === 'day' && (date.getDay() === 0 || date
								.getDay() === 6));
					};

					$scope.openCalendar = function($event) {

						$event.preventDefault();
						$event.stopPropagation();

						$scope.opened = true;
					};

					$scope.$watch('center.zoom', function(newVal, oldVal) {
						$scope.s2zoom = $scope.center.zoom + 1;
						// if($scope.s2zoom>=MAXS2LEVEL){$scope.s2zoom=MAXS2LEVEL.toString()+"
						// (max)";}

					})

					$scope.$watch('bounds', function(newVal, oldVal) {
						// if($scope.center.zoom>=10){
						getGeoHashes();
						// }

					})
					$scope.$watch('search', function(newVal, oldVal) {
						// if($scope.center.zoom>=10){
						getGeoHashes();
						// }
					}, true)

					function countstyle(feature) {
						var _style = {
							weight : 2,
							opacity : 1,
							color : 'orange',
							dashArray : '3',
							fillOpacity : 0.0
						}

						var llstyle = angular.copy(_style);

						if (feature.count !== 0) {
							llstyle.color = 'blue';
							llstyle.fillOpacity = feature.count * 0.0001;
							if (llstyle.fillOpacity <= 0.1)
								llstyle.fillOpacity = 0.1;
							if (llstyle.fillOpacity >= 0.8)
								llstyle.fillOpacity = 0.8;
						}
						return llstyle
					}

					function onEachFeature(feature, layer) {
						var popup = ' Metingen:  '
								+ feature.count
								+ "
"
								// + ' Eerste meting:  ' +
								// $filter('date')(feature.firstseen,'dd-MM-yyyy
								// hh:mm:ss')+ "
"
								+ ' Laatste meting:  '
								+ $filter('date')(feature.lastseen,
										'dd-MM-yyyy hh:mm:ss') + "
"

						layer.bindPopup(popup);
					}

					// function getCount(){
					// getGeoHashes();
					// // if($scope.bounds){
					// // $scope.mouseclass="wait";

					// // var params={};
					// //
					// params.sw=[$scope.bounds.southWest.lng,$scope.bounds.southWest.lat];
					// //
					// params.ne=[$scope.bounds.northEast.lng,$scope.bounds.northEast.lat];
					// // params.center=$scope.center;

					// // if($scope.search.mccmnc){
					// // console.log($scope.search.mccmnc)
					// // params.mnc=$scope.search.mccmnc.mnc;
					// // params.mcc=$scope.search.mccmnc.mcc;
					// // }
					// // if($scope.search.dt){
					// // params.dt=new Date($scope.search.dt).getTime();
					// // params.range=$scope.search.range;
					// // }
					// // if($scope.search.serving!=='all')
					// // params.serving=$scope.search.serving==="true"
					// // if($scope.search.network!=='all')
					// // params.network=$scope.search.network
					// // $http.get('/api/measurements',{
					// // params:params
					// // })
					// // .error(function(err){
					// // console.log(err);
					// // })
					// // .success(function(results) {

					// // //GET DISTINCT CELL COUNT
					// // $http.get('/api/measurementdistinctcount',{
					// // params:params
					// // })
					// // .error(function(err){
					// // console.log(err);
					// // })
					// // .success(function(cnt){
					// // $scope.distinctcount=cnt;
					// // })
					// // //END

					// // $scope.measurementcount=results.resultsLength;
					// // var features=[]
					// // angular.forEach(results.covers,function(item,key){
					// // var feature={}
					// // feature.type="Feature";
					// // feature.id=key;
					// // feature.count=item.count;
					// // feature.lastseen=item.lastSeen;
					// // feature.geometry=item.geometry;
					// // features.push(feature);
					// // })

					// // angular.extend($scope,{
					// // geojson:{
					// // data:features,
					// // style:countstyle,
					// // onEachFeature:onEachFeature
					// // }
					// // })
					// // $scope.mouseclass=null;
					// // });
					// // }
					// };

					// MAP STUFF

					var markers = {};
					var paths = {};

					angular.extend($scope, {
						defaults : {
							scrollWheelZoom : false
						},

						controls : {
							fullscreen : {},
						},
						paths : paths,
						markers : markers,
						center : MAPSERVER.center,
						bounds : $scope.bounds,

						layers : {
							baselayers : {
								osm : MAPSERVER.osm,
								// basic:MAPSERVER.mapbox_streets_basics,
								luchtfoto : MAPSERVER.luchtfoto
							},
						},
						events : {
							// map: {
							// enable: ['click'],
							// logic:'emit'
							// },
							marker : {
								disable : leafletEvents
										.getAvailableMarkerEvents()
							},
							path : {
								disable : leafletEvents
										.getAvailablePathEvents()
							}
						}
					});

					$scope.$on('leafletDirectiveMap.baselayerchange', function(
							event, args) {
						if (args.leafletEvent.name === 'OSM') {
							$scope.desaturate = true;
						} else {
							$scope.desaturate = false;
						}
						;
					});

					// END MAP STUFF

				})<commit_msg>fixed bug in cell coverage when no results are found in selection<commit_after>//cells.js
'use strict';
/* jshint indent: false */

angular
		.module('celllogger')

		.controller(
				'CellloggerCtrl',
				function($scope, $http, leafletData, $filter, AlertService,
						MAPSERVER, MAXS2LEVEL, leafletEvents, WEBSERVICE,
						$interval) {

					$scope.desaturate = true;
					$scope.controller = 'CellloggerCtrl';
					$scope.search = {
						range : 365,
						serving : "all",
						network : "all"
					};
					$scope.providers = [];
					$scope.s2zoom = MAPSERVER.center.zoom;
					$scope.mouseclass = null;

					function getProviders() {
						$http
								.get(WEBSERVICE + '/measurementproviders', {})
								.error(function(err) {
									console.log(err);
								})
								.success(
										function(result) {
											// console.log(result);
											angular
													.forEach(
														result.providers.buckets,
														function(provider) {
//															$scope.providers
//																	.push({
//																		name : provider.key,
//																		mccmnc : provider.key
//																	});
															$http
																	.get( WEBSERVICE + '/provider',{ params:{ _id:provider.key}})
																	.error(	function(err) {
																		console.log(err);
																	})
																	.success(function(result) {
																			if (result.hits.total == "1"){
																			$scope.providers.push({
																				name : result.hits.hits[0]._source.name,
																				mccmnc : provider.key

																			});
																			} else {
																				$scope.providers.push({
																					name : provider.key,
																					mccmnc : provider.key

																				});
																			}
																		})

														})
											// result.forEach(function(provider){
											// $scope.providers.push({name:provider.name,mccmnc:{mcc:provider.mcc,mnc:provider.mnc}});
											// })

										})
					}
					getProviders();

					$scope.dateOptions = {
						formatYear : 'yy',
						startingDay : 1
					};

					$scope.formats = [ 'dd-MM-yyyy', 'yyyy/MM/dd',
							'dd.MM.yyyy', 'shortDate' ];
					$scope.format = $scope.formats[0];

					function getGeoHashes() {
						$http.defaults.useXDomain = true;

						if ($scope.bounds) {
							$scope.mouseclass = "wait";
							var gp = 6;
							switch (true) {
							case ($scope.s2zoom < 5):
								gp = 2;
								break;
							case ($scope.s2zoom > 4 && $scope.s2zoom < 7):
								gp = 3;
								break;
							case ($scope.s2zoom > 6 && $scope.s2zoom < 9):
								gp = 4;
								break;
							case ($scope.s2zoom > 8 && $scope.s2zoom < 12):
								gp = 5;
								break;
							case ($scope.s2zoom > 11 && $scope.s2zoom < 14):
								gp = 6;
								break;
							case ($scope.s2zoom > 14):
								gp = 7;
								break;
							}

							var params = {
								datePrecision : 730,
								geohashPrecision : (gp),
								bottom_left : [ $scope.bounds.southWest.lat,
										$scope.bounds.southWest.lng ],
								top_right : [ $scope.bounds.northEast.lat,
										$scope.bounds.northEast.lng ]
							};

							if ($scope.search.mccmnc) {
								params.net = $scope.search.mccmnc.split('-')[1];
								params.mcc = $scope.search.mccmnc.split('-')[0];
							}
							if ($scope.search.dt) {
								params.timestamp = new Date($scope.search.dt)
										.getTime();
							}
							if ($scope.search.range) {
								params.datePrecision = $scope.search.range;
							}
							if ($scope.search.serving !== 'all')
								params.serving = $scope.search.serving === "true"
							if ($scope.search.network !== 'all')
								params.radio = $scope.search.network

							$http.get(WEBSERVICE + '/measurementcellcount', {
								params : params
							}).error(function(err) {
								console.log(err);
							}).success(function(result) {
								$scope.distinctcount = result.cells.value;
							})

							$http
									.get(WEBSERVICE + '/coverage', {
										params : params
									})
									.error(function(err) {
										console.log(err);
									})
									.success(
											function(result) {
												$scope.measurementcount = result.hits.total;

												if ($scope.measurementcount == "0"){
													angular
													.extend(
															$scope,
															{
																geohash : {
																	data : null,
																	options : null
																}
															})
												} else {

												var maxValue = result.aggregations.cellgrid.buckets[0].doc_count;

												var colorFunction = new L.HSLHueFunction(
														new L.Point(1, 120),
														new L.Point(maxValue, 0),
														{
															outputSaturation : '100%',
															outputLuminosity : '50%'
														});
												var fillColorFunction = new L.HSLHueFunction(
														new L.Point(1, 120),
														new L.Point(maxValue, 0),
														{
															outputSaturation : '100%',
															outputLuminosity : '50%'
														});
												function geoHashOptions() {
													var options = {
														recordsField : 'buckets',
														geohashField : 'key',
														displayOptions : {
															doc_count : {
																color : colorFunction,
																fillColor : fillColorFunction,
																gradient : false
															}
														},
														layerOptions : {
															fillOpacity : 0.5,
															opacity : 1,
															weight : 1,
															gradient : true
														}
													};
													return options;
												}

												angular
														.extend(
																$scope,
																{
																	geohash : {
																		data : result.aggregations.cellgrid,
																		options : geoHashOptions()
																	}
																})
												}
											})
							$scope.mouseclass = null;
						}
					}

					// function getTotalinScope(){
					// var gp=6;
					// switch(true){
					// case ($scope.s2zoom<5):
					// gp=2;
					// break;
					// case ($scope.s2zoom>4 && $scope.s2zoom<7):
					// gp=3;
					// break;
					// case ($scope.s2zoom>6 && $scope.s2zoom<9):
					// gp=4;
					// break;
					// case ($scope.s2zoom>8 && $scope.s2zoom<12):
					// gp=5;
					// break;
					// case ($scope.s2zoom>11&& $scope.s2zoom<14):
					// gp=6;
					// break;
					// case ($scope.s2zoom>14):
					// gp=7;
					// break;
					// }

					// var params={
					// datePrecision:365,
					// geohashPrecision:(gp),
					// bottom_left:[$scope.bounds.southWest.lat,$scope.bounds.southWest.lng],
					// top_right:[$scope.bounds.northEast.lat,$scope.bounds.northEast.lng]
					// };

					// if($scope.search.mccmnc){
					// params.net=$scope.search.mccmnc.mnc;
					// params.mcc=$scope.search.mccmnc.mcc;
					// }
					// if($scope.search.dt){
					// params.timestamp=new Date($scope.search.dt).getTime();
					// }
					// if($scope.search.serving!=='all')
					// params.serving=$scope.search.serving==="true"
					// if($scope.search.network!=='all')
					// params.radio=$scope.search.network
					// console.log(params);
					// $http.get(WEBSERVICE + '/measurementcellcount',{
					// params: params
					// })
					// .error(function(err){
					// console.log(err);
					// })
					// .success(function(result){
					// console.log(result);
					// $scope.distinctcount=result.cells.value;

					// })
					// }

					function getTotal() {
						var params = {
							datePrecision : 7000
						}

						$http.get(WEBSERVICE + '/measurementcount', {
							params : params
						}).error(function(err) {
							console.log(err);
						}).success(function(result) {
							$scope.total = result.total;
						})
					}

					getTotal();
					getGeoHashes();

					// Regular updates
					$scope.stopUpdate = function() {
						if (angular.isDefined(stop)) {
							$interval.cancel(stop);
							stop = undefined;
						}
					}

					var stop = $interval(function() {
						getTotal();
						// getTotalinScope();
					}, 3000);

					$scope.$on("$destroy", function() {
						$scope.stopUpdate();
					});

					$scope.$watch('search', function(value) {
						getGeoHashes();
					})

					$scope.refresh = function() {
						getGeoHashes();
					}

					$scope.today = function() {
						$scope.dt = new Date();
					};
					$scope.today();

					$scope.clear = function() {
						$scope.search.dt = null;
					};

					// Disable weekend selection
					$scope.disabled = function(date, mode) {
						return (mode === 'day' && (date.getDay() === 0 || date
								.getDay() === 6));
					};

					$scope.openCalendar = function($event) {

						$event.preventDefault();
						$event.stopPropagation();

						$scope.opened = true;
					};

					$scope.$watch('center.zoom', function(newVal, oldVal) {
						$scope.s2zoom = $scope.center.zoom + 1;
						// if($scope.s2zoom>=MAXS2LEVEL){$scope.s2zoom=MAXS2LEVEL.toString()+"
						// (max)";}

					})

					$scope.$watch('bounds', function(newVal, oldVal) {
						// if($scope.center.zoom>=10){
						getGeoHashes();
						// }

					})
					$scope.$watch('search', function(newVal, oldVal) {
						// if($scope.center.zoom>=10){
						getGeoHashes();
						// }
					}, true)

					function countstyle(feature) {
						var _style = {
							weight : 2,
							opacity : 1,
							color : 'orange',
							dashArray : '3',
							fillOpacity : 0.0
						}

						var llstyle = angular.copy(_style);

						if (feature.count !== 0) {
							llstyle.color = 'blue';
							llstyle.fillOpacity = feature.count * 0.0001;
							if (llstyle.fillOpacity <= 0.1)
								llstyle.fillOpacity = 0.1;
							if (llstyle.fillOpacity >= 0.8)
								llstyle.fillOpacity = 0.8;
						}
						return llstyle
					}

					function onEachFeature(feature, layer) {
						var popup = ' Metingen:  '
								+ feature.count
								+ "
"
								// + ' Eerste meting:  ' +
								// $filter('date')(feature.firstseen,'dd-MM-yyyy
								// hh:mm:ss')+ "
"
								+ ' Laatste meting:  '
								+ $filter('date')(feature.lastseen,
										'dd-MM-yyyy hh:mm:ss') + "
"

						layer.bindPopup(popup);
					}

					// function getCount(){
					// getGeoHashes();
					// // if($scope.bounds){
					// // $scope.mouseclass="wait";

					// // var params={};
					// //
					// params.sw=[$scope.bounds.southWest.lng,$scope.bounds.southWest.lat];
					// //
					// params.ne=[$scope.bounds.northEast.lng,$scope.bounds.northEast.lat];
					// // params.center=$scope.center;

					// // if($scope.search.mccmnc){
					// // console.log($scope.search.mccmnc)
					// // params.mnc=$scope.search.mccmnc.mnc;
					// // params.mcc=$scope.search.mccmnc.mcc;
					// // }
					// // if($scope.search.dt){
					// // params.dt=new Date($scope.search.dt).getTime();
					// // params.range=$scope.search.range;
					// // }
					// // if($scope.search.serving!=='all')
					// // params.serving=$scope.search.serving==="true"
					// // if($scope.search.network!=='all')
					// // params.network=$scope.search.network
					// // $http.get('/api/measurements',{
					// // params:params
					// // })
					// // .error(function(err){
					// // console.log(err);
					// // })
					// // .success(function(results) {

					// // //GET DISTINCT CELL COUNT
					// // $http.get('/api/measurementdistinctcount',{
					// // params:params
					// // })
					// // .error(function(err){
					// // console.log(err);
					// // })
					// // .success(function(cnt){
					// // $scope.distinctcount=cnt;
					// // })
					// // //END

					// // $scope.measurementcount=results.resultsLength;
					// // var features=[]
					// // angular.forEach(results.covers,function(item,key){
					// // var feature={}
					// // feature.type="Feature";
					// // feature.id=key;
					// // feature.count=item.count;
					// // feature.lastseen=item.lastSeen;
					// // feature.geometry=item.geometry;
					// // features.push(feature);
					// // })

					// // angular.extend($scope,{
					// // geojson:{
					// // data:features,
					// // style:countstyle,
					// // onEachFeature:onEachFeature
					// // }
					// // })
					// // $scope.mouseclass=null;
					// // });
					// // }
					// };

					// MAP STUFF

					var markers = {};
					var paths = {};

					angular.extend($scope, {
						defaults : {
							scrollWheelZoom : false
						},

						controls : {
							fullscreen : {},
						},
						paths : paths,
						markers : markers,
						center : MAPSERVER.center,
						bounds : $scope.bounds,

						layers : {
							baselayers : {
								osm : MAPSERVER.osm,
								// basic:MAPSERVER.mapbox_streets_basics,
								luchtfoto : MAPSERVER.luchtfoto
							},
						},
						events : {
							// map: {
							// enable: ['click'],
							// logic:'emit'
							// },
							marker : {
								disable : leafletEvents
										.getAvailableMarkerEvents()
							},
							path : {
								disable : leafletEvents
										.getAvailablePathEvents()
							}
						}
					});

					$scope.$on('leafletDirectiveMap.baselayerchange', function(
							event, args) {
						if (args.leafletEvent.name === 'OSM') {
							$scope.desaturate = true;
						} else {
							$scope.desaturate = false;
						}
						;
					});

					// END MAP STUFF

				})<|endoftext|>


<commit_before>'use strict';
var footerCtrl = function($scope, globalService) {
    var gasPriceKey = "gasPrice";
    $scope.footerModal = new Modal(document.getElementById('disclaimerModal'));
    $scope.ethBlockNumber = "loading";
    $scope.etcBlockNumber = "loading";
    $scope.showBlocks = window.location.protocol == "https:";
    $scope.setBlockNumbers = function() {
        if (!$scope.showBlocks) return;
        ajaxReq.getCurrentBlock(function(data) { $scope.currentBlockNumber = data.data; });
    }
    $scope.setBlockNumbers();
    $scope.globalService = globalService;

    $scope.curLang = globalFuncs.curLang;
    $scope.gasChanged = function() {
        globalFuncs.localStorage.setItem(gasPriceKey, $scope.gas.value);
        ethFuncs.gasAdjustment = $scope.gas.value;
    }
    var setGasValues = function() {
        $scope.gas = {
            curVal: 21,
            value: globalFuncs.localStorage.getItem(gasPriceKey, null) ? parseInt(globalFuncs.localStorage.getItem(gasPriceKey)) : 21,
            max: 60,
            min: 1
        }
        ethFuncs.gasAdjustment = $scope.gas.value;
    }
    setGasValues();
    $scope.gasChanged();
};
module.exports = footerCtrl;
<commit_msg>Update footerCtrl.js<commit_after>'use strict';
var footerCtrl = function($scope, globalService) {
    var gasPriceKey = "gasPrice";
    $scope.footerModal = new Modal(document.getElementById('disclaimerModal'));
    $scope.ethBlockNumber = "loading";
    $scope.etcBlockNumber = "loading";
    $scope.showBlocks = window.location.protocol == "https:";
    $scope.setBlockNumbers = function() {
        if (!$scope.showBlocks) return;
        ajaxReq.getCurrentBlock(function(data) { $scope.currentBlockNumber = data.data; });
    }
    $scope.setBlockNumbers();
    $scope.globalService = globalService;

    $scope.curLang = globalFuncs.curLang;
    $scope.gasChanged = function() {
        globalFuncs.localStorage.setItem(gasPriceKey, $scope.gas.value);
        ethFuncs.gasAdjustment = $scope.gas.value;
    }
    var setGasValues = function() {
        $scope.gas = {
            curVal: 21,
            value: globalFuncs.localStorage.getItem(gasPriceKey, null) ? parseInt(globalFuncs.localStorage.getItem(gasPriceKey)) : 21,
            max: 60,
            min: 0.1,
            step: 0.1
        }
        ethFuncs.gasAdjustment = $scope.gas.value;
    }
    setGasValues();
    $scope.gasChanged();
};
module.exports = footerCtrl;
<|endoftext|>