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

    this.$scope.list = [];
    this.$scope.headers = [
      'name',
      'display_name',
      'voip_ip'
    ];
    this.$scope.actions = [
      'edit',
      'delete'
    ];
    this.$scope.path = '/xivo/configuration/index.php/manage/mediaserver/';
    this.$scope.delete = (id) => {
      this.mediaServers.deleteMediaServer(id).then(() => {
        this.$window.location.href = '?act=list';
      }, (error) => {
        if (error.data.match(/trunkfeatures_mediaserverid_fkey/g)) {
          this.toolbar.setError('fm_mediaserver_used_by_sip_trunk_error');
        }
        else if (error.data.match(/groupfeatures_mediaserverid_fkey/g)) {
          this.toolbar.setError('fm_mediaserver_used_by_group_error');
        }
        else {
          this.toolbar.setError("fm_generic_error");
          $log.error(error);
        }
      });
    };

    this.$scope.isLoading = true;
    mediaServers.listMediaServers()
      .then((response) => {
        this.$scope.list = response.data;
        this.$scope.isLoading = false;
      }, (error) => {
        this.toolbar.setError("fm_generic_error");
        $log.error(error);
      });
  }
}
