import {router} from './routes';
import {
  APIService,
  AuthorizationService,
  CommandService,
  ConfigService,
  MakeflowService,
  TokenService,
} from './services';

export const apiService = new APIService(router);

export const tokenService = new TokenService(apiService);

export const commandService = new CommandService(apiService);

export const authorizationService = new AuthorizationService(apiService);

export const makeflowService = new MakeflowService(apiService);

export const configService = new ConfigService(apiService);

// Route services

router.commands.$intercept(match => {
  if (match.$exact) {
    router.commands.history.$replace();
  }
});

router.commands.history.commandId.$intercept(match => {
  let commandId = Number(match.$params.commandId);

  commandService.fetchCommandHistoryItem(commandId).catch(console.error);
});

router.commands.history.$intercept(() => {
  commandService.fetchLatestCommandsHistory().catch(console.error);
});

router.commands.management.$intercept(() => {
  commandService.fetchCommands().catch(console.error);
});

router.tokens.$intercept(() => {
  tokenService.fetchTokens().catch(console.error);
});

router.$rest.$intercept(() => {
  router.home.$replace();
});
