const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const methodOverride = require('method-override');
const config = require('./config');
const multer = require('multer');
const {GridFsStorage} = require('multer-gridfs-storage');
const crypto = require('crypto');
const  cors = require('cors');
const  bodyParser = require('body-parser');
const mongoose =require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5001;


app.use(bodyParser.urlencoded({ extended: true }));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(cors({
    origin: '*',
}));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(methodOverride('_method'));
app.use(express.static(path.join(__dirname, 'public')));

mongoose.Promise = require('bluebird');

const url = config.mongoURI;
const connect = mongoose.connect(url, { useNewUrlParser:true, useUnifiedTopology: true, useCreateIndex:true, useFindAndModify: false });

connect.then(() => {
    console.log('Connected to database: GridApp');
}, (err) => console.log(err));

// create storage engine
const storage = new GridFsStorage({
    url: config.mongoURI,
    file: (req, file) => {
        return new Promise((resolve, reject) => {
            crypto.randomBytes(16, (err, buf) => {
                if (err) {
                    return reject(err);
                }
                const filename = buf.toString('hex') + path.extname(file.originalname);
                const fileInfo = {
                    filename: filename,
                    bucketName: 'uploads'
                };
                resolve(fileInfo);
            });
        });
    }
});

const upload = multer({ storage });


// const connection = mongoose.connection;
// connection.once('open',() => {
//     console.log("MongoDB database connection established successfully");
// }).catch(err => {
//     console.error('App starting error:', err.stack);
//     process.exit(1);
// });



const studentRouter = require('./routes/student.route');
const tutorRouter = require('./routes/tutor.route');
const instituteRouter = require('./routes/institute.route');
const userAccount = require('./routes/userAccount.route');
const questionManage = require('./routes/question.route');
const financeRouter = require('./routes/finance.route');
const studentResult = require('./routes/studentALResult.route');
const tutorRating = require('./routes/tutorRatings.route');
const filteredList = require('./routes/filteredListNew.route');
const createClassRoute = require('./routes/createClass.route');
const studPerRoute = require('./routes/studper.route');

const imageRouter = require('./routes/pdf.route');
const answerManage = require('./routes/answer_route');

app.use('/studentSingUp',studentRouter);
app.use('/tutorSingUp',tutorRouter);
app.use('/instituteSingUp',instituteRouter);
app.use('/userAccount',userAccount);
app.use('/questions', questionManage);
app.use('/answer', answerManage);
app.use('/admin/finance', financeRouter);
app.use('/studentResults', studentResult);
app.use('/tutorRatings', tutorRating);
app.use('/filteredList', filteredList);
app.use('/createClass', createClassRoute);
app.use('/admin/studper',studPerRoute);
app.use('/', imageRouter(upload));

app.listen(port, () => {
    console.log(`Server is running on Port: ${port}`);
});
