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

    this.$scope.errors = [];
    this.$scope.routeForm = {
      dialpattern: [],
      context: [],
      mediaserver: [],
      trunk: []
    };

    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.getTemplate().then(tpl => {
      this.$scope.template = tpl;
    }, (error)  =>  {
      this.toolbar.setError('fm_generic_error');
      this.$log.error(error);
    });
  }

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

  createRoute() {
    let route = Object.assign({priority: this.$scope.template.priority}, this.$scope.routeForm);
    this.route.createRoute(route).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.createRoute();
    }
  }
}
