import express from 'express';
import { isAuthenticated } from '../../keycloak.js';
import { convertPropertiesString, getFilter, parseFilter } from '../../utils.js';

const router = express.Router();
import {
  listFilamentsRouteHandler,
  listFilamentsByPropertiesRouteHandler,
  getFilamentRouteHandler,
  editFilamentRouteHandler,
  newFilamentRouteHandler,
  getFilamentStatsRouteHandler,
  getFilamentHistoryRouteHandler,
} from '../../services/management/filaments.js';

// list of filaments
router.get('/', isAuthenticated, (req, res) => {
  const { page, limit, property, search, sort, order } = req.query;

  const allowedFilters = [
    '_id',
    'type',
    'vendor.name',
    'diameter',
    'color',
    'name',
    'vendor._id',
    'cost',
  ];

  var filter = {};

  for (const [key, value] of Object.entries(req.query)) {
    for (var i = 0; i < allowedFilters.length; i++) {
      if (key == allowedFilters[i]) {
        filter = { ...filter, ...parseFilter(key, value) };
      }
    }
  }

  listFilamentsRouteHandler(req, res, page, limit, property, filter, search, sort, order);
});

router.get('/properties', isAuthenticated, (req, res) => {
  let properties = convertPropertiesString(req.query.properties);
  const allowedFilters = ['diameter', 'type', 'vendor'];
  const filter = getFilter(req.query, allowedFilters, false);
  listFilamentsByPropertiesRouteHandler(req, res, properties, filter);
});

router.post('/', isAuthenticated, (req, res) => {
  newFilamentRouteHandler(req, res);
});

// get filament stats
router.get('/stats', isAuthenticated, (req, res) => {
  getFilamentStatsRouteHandler(req, res);
});

// get filaments history
router.get('/history', isAuthenticated, (req, res) => {
  getFilamentHistoryRouteHandler(req, res);
});

router.get('/:id', isAuthenticated, (req, res) => {
  getFilamentRouteHandler(req, res);
});

// update printer info
router.put('/:id', isAuthenticated, async (req, res) => {
  editFilamentRouteHandler(req, res);
});

export default router;
