import {Router} from 'express'
const { connect, disconnect } = require('../config/db');
import CardRepository from '../repository/CardRepository'
import CardService from '../service/CardService'
import CardController from '../controller/CardController'

import FileController from '../controller/FileController'
import FileService from '../service/FileService'
import FileRepository from "../repository/FileRepository";
import multer from 'multer';

import UserRepository from '../repository/UserRepository'
import UserService from '../service/UserService'
import UserController from '../controller/UserController'

import AuthController from '../controller/AuthController'

let router: Router;
router = Router();
connect()

let fileRepository = new FileRepository()
let fileService = new FileService(fileRepository)
let fileController = new FileController(fileService)
let cardRepository = new CardRepository()
let cardService = new CardService(cardRepository)
let cardController = new CardController(cardService, fileService)

let userRepository = new UserRepository()
let userService = new UserService(userRepository)
let userController = new UserController(userService)

let upload = multer({ dest : './uploads/' })

let auth = new AuthController(userRepository)

async function importDefault() {
    let user = await userRepository.getFirst({username: "admin"});
    if(!user) await userRepository.create({username: "admin", password: "admin"})
}

importDefault();

router.post('/login', auth.login.bind(auth))
router.use(auth.isAuthenticated.bind(auth))

router.get('/card/', cardController.getAll.bind(cardController))
router.get('/card/:id/front', cardController.getFrontImage.bind(cardController))
router.get('/card/:id/back', cardController.getBackImage.bind(cardController))
router.get('/card/:id', cardController.getById.bind(cardController));
router.post('/card/', cardController.create.bind(cardController));
router.put('/card/:id', cardController.update.bind(cardController))
router.delete('/card/:id', cardController.delete.bind(cardController));

router.get('/file/', fileController.getAll.bind(fileController));
router.get('/file/:id',  fileController.getById.bind(fileController));
router.get('/file/:id/base64',  fileController.getBase64.bind(fileController));
router.get('/file/:id/content',  fileController.getContent.bind(fileController));
router.post('/file/', upload.single("file"), fileController.create.bind(fileController));
router.delete('/file/:id', fileController.delete.bind(fileController));

router.get('/user/', userController.getAll.bind(userController))
router.get('/user/:id', userController.getById.bind(userController));
router.post('/user/', userController.create.bind(userController));
router.put('/user/:id', userController.update.bind(userController))
router.delete('/user/:id', userController.delete.bind(userController));


router.get('/logout', auth.logout.bind(auth))

export default router;
