export default class IpbxEditRouteController {
  constructor(route, $scope, $window, $log, toolbar) {
    this.route = route;
    this.$scope = $scope;
    this.$window = $window;
    this.$log = $log;
    this.toolbar = toolbar;

    this.params = this.toolbar.parseParams($window.location.search);

    this.$scope.errors = [];
    this.$scope.routeForm = {};

    this.$scope.columns = [
      {length: 38, name: "pattern", placeholder: "X.", required: true},
      { length: 18, name: "regexp", tooltip: true },
      {length: 12, name: "target", tooltip: true},
      {length: 14, name: "callerid"}
    ];

    this.route.getRoute(this.params.id).then(form => {
      this.$scope.prevForm = form;
      this.$scope.routeForm = {
        priority: form.priority,
        internal: form.internal,
        dialpattern: form.dialpattern,
        context: form.context.filter(i => i.used),
        mediaserver: form.mediaserver.filter(i => i.used),
        trunk: form.trunk.filter(i => i.used),
        subroutine: form.subroutine,
        description: form.description,
        right: form.right.filter(i => i.used),
        schedule: form.schedule.filter(i => i.used).pop()
      };
      this.$scope.prevForm.trunk = angular.copy(form.trunk.filter(i => !i.used));
    }, (error)  =>  {
      this.toolbar.setError('fm_generic_error');
      this.$log.error(error);
    });
  }

  hasTrunk() {
    if (!this.$scope.prevForm) return true; //while loading
    return this.$scope.prevForm.trunk.length > 0 || this.$scope.routeForm.trunk.length > 0;
  }

  updateRoute() {
    this.route.updateRoute(this.$scope.prevForm , angular.copy(this.$scope.routeForm)).then(() => {
      this.$window.location.href = '?act=list';
    }, (error) => {
      this.toolbar.setError('fm_generic_error');
      this.$log.error(error);
    });
  }

  checkRequired(routeForm) {
    this.$scope.errors = this.route.checkRoute(routeForm);
  }

  validate() {
    this.$scope.errors = [];
    this.checkRequired(this.$scope.routeForm);

    if (!this.$scope.errors.length) {
      this.updateRoute();
    }
  }
}
