import _ from 'lodash';

export default function route($http, $translate) {
  const xivoApiUri = '/configmgt/api/1.0/route/';

  const _path = 'service/ipbx/index.php/call_management/route/';
  const _optionalFields = ["context", "mediaserver", "subroutine", "description", "right", "schedule", "target", "regexp", "callerid"];
  const _noPostProcessFields = ["description", "id", "dialpattern", "priority", "subroutine", "internal"];

  const  _getTemplate = () => {
    return $http.get(xivoApiUri+'new/').then((result) => {
      return result.data;
    });
  };

  const  _getRoute = (id) => {
    return $http.get(xivoApiUri+id).then((result) => {
      result.data.dialpattern = result.data.dialpattern.map((r, index) => { r.id = index+1; return r; });
      return result.data;
    });
  };

  const _listRoutes = () => {
    return $http.get(xivoApiUri).then((result) => {
      var routeList = result.data;

      routeList.map(route => {
        route.dialpattern = _.flatMap(route.dialpattern, (i => i.pattern));
        route.context = _.flatMap(route.context.filter(i => i.used), (i => i.name));
        if (!route.context.length) route.context.push($translate.instant('all'));
        route.mediaserver = _.flatMap(route.mediaserver.filter(i => i.used), (i => i.display_name));
        if (!route.mediaserver.length) route.mediaserver.push($translate.instant('all'));
        route.trunk = _.flatMap(route.trunk.filter(i => i.used),(i => i.name));
      });

      return routeList;
    });
  };

  const _buildRoute = (route) => {
    const _isEmptyFieldValue = (value, key) => {
      return _optionalFields.includes(key) && _isEmpty(value);
    };

    route.dialpattern = route.dialpattern
                        .filter((r) => r.pattern)
                        .map((r) => _.omit(r, 'id'))
                        .map((r) => _.omitBy(r, _isEmptyFieldValue));

    if (!_isEmpty(route.schedule)) route.schedule = [route.schedule];

    for (var key in route) {
      if (!_noPostProcessFields.includes(key)){
        if (!_isEmpty(route[key])) route[key].map(i => i.used = true);
      }
    }
    return route;
  };

  const _createRoute = (route) => {
    return $http.post(xivoApiUri, angular.toJson(_buildRoute(route)));
  };

  const _updateRoute = (oldRoute, newRoute) => {
    newRoute.id = oldRoute.id;
    return $http.put(xivoApiUri, angular.toJson(_buildRoute(newRoute)));
  };

  const _deleteRoute = (id) => {
    return $http.delete(xivoApiUri+id);
  };

  const _checkRoute = (route) => {
    let errors = [];
    for (var key in route) {
      if (_optionalFields.includes(key)) continue;
      if ((key == 'dialpattern' && !route[key].filter((r) => r.pattern).length) ||
        _isEmpty (route[key])) {
        errors.push(key);
      }
    }
    return errors;
  };

  const _isEmpty = (value) => {
    return  value === undefined ||
            value === null ||
            (typeof value === "object" && Object.keys(value).length === 0) ||
            (typeof value === "string" && value.trim().length === 0);
  };

  return {
    getRoute: _getRoute,
    listRoutes: _listRoutes,
    createRoute: _createRoute,
    updateRoute: _updateRoute,
    deleteRoute: _deleteRoute,
    checkRoute: _checkRoute,
    getTemplate: _getTemplate,
    path: _path
  };
}
