let $injector = widgetContext.$scope.$injector;
let customDialog = $injector.get(widgetContext.servicesMap.get('customDialog'));
let assetService = $injector.get(widgetContext.servicesMap.get('assetService'));
let attributeService = $injector.get(widgetContext.servicesMap.get('attributeService'));
let entityService = $injector.get(widgetContext.servicesMap.get('entityService'));
console.log(widgetContext);
openAddEntityDialog();

function openAddEntityDialog() {
  customDialog.customDialog(htmlTemplate, AddEntityDialogController).subscribe(() => {});
}

function AddEntityDialogController(instance) {
  let vm = instance;

  vm.entityName = entityName;

  vm.attributes = {};
  vm.timeseries = {};
  
  vm.editEntity = vm.fb.group({
    attributes: vm.fb.group({
      note: ""
    })
  });

  getEntityInfo();

  vm.cancel = function() {
    vm.dialogRef.close(null);
  };

  vm.save = function() {
    vm.loading = true;
    saveAttributes(entityId).subscribe(
      () => {
        vm.dialogRef.close(null);
      }, () =>{
        vm.loading = false;
      }
    );
  };

  function getEntityAttributes(attributes) {
    for (var i = 0; i < attributes.length; i++) {
      vm.attributes[attributes[i].key] = attributes[i].value;
    }
  }

  function getEntityInfo() {
    vm.loading = true;
    attributeService.getEntityAttributes(entityId, 'SERVER_SCOPE').subscribe(
      function (data) {
          console.log(data);
        getEntityAttributes(data);

        vm.editEntity.patchValue({
          attributes: vm.attributes
        }, {emitEvent: false});
        vm.loading = false;
      }
    );
    /*attributeService.getEntityTimeseries(entityId, ["LOGS"],Date.now() - 24*60*60*1000, Date.now() ).subscribe(
      function (data) {
          console.log(data);
        //getEntityTimeseries(data);

        vm.editEntity.patchValue({
          timeseries: vm.timeseries
        }, {emitEvent: false});
        vm.loading = false;
      }
    );*/
  }

  function saveAttributes(entityId) {
    let attributes = vm.editEntity.get('attributes').value;
    let attributesArray = [];
    for (let key in attributes) {
      if (attributes[key] !== vm.attributes[key]) {
        attributesArray.push({key: key, value: attributes[key]});
      }
    }
    /*if (attributesArray.length > 0) {
      return attributeService.saveEntityAttributes(entityId, "SERVER_SCOPE", attributesArray);
    }*/
    return attributeService.saveEntityTimeseries(entityId,"ANY", [{"lastUpdateTs": Date.now(), "key": widgetContext.datasources[0].dataKeys[0].name, "value": attributes.note}] );
    //return widgetContext.rxjs.of([]);
  }
}
