require('./config/config');

const _ = require('lodash');
const cors = require('cors');

const fs = require('fs');

//const throttle = require('express-throttle-bandwidth');

const port = process.env.PORT;


const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');

const sendemail = require('./sendemail');

const cron = require('node-cron');

i18n = require("i18n");

if ((process.env.NODE_ENV === 'production') || (process.env.NODE_ENV === 'test')) {
  var privateKey = fs.readFileSync(process.env.PATH_CERT_KEY, 'utf8');
  var certificate = fs.readFileSync(process.env.PATH_SERVER_CRT, 'utf8');
  var credentials = { key: privateKey, cert: certificate };
  var https = require('https');
} else {
  var http = require('http');
}

require('./models/todo');
require('./models/project');
require('./models/user');
require('./models/subscribers');
require('./models/cfgserver');
require('./models/booking');
require('./models/sendmsg');
require('./models/mailinglist');
require('./models/newstosent');
require('./models/mypage');
require('./models/calzoom');
const mysql_func = require('./mysql/mysql_func');

const { Newstosent } = require('./models/newstosent');

const index_router = require('./router/index_router');
const push_router = require('./router/push_router');
const newsletter_router = require('./router/newsletter_router');
const booking_router = require('./router/booking_router');
const dashboard_router = require('./router/dashboard_router');
const myevent_router = require('./router/myevent_router');
const subscribe_router = require('./router/subscribe_router');
const sendmsg_router = require('./router/sendmsg_router');
const email_router = require('./router/email_router');
const todos_router = require('./router/todos_router');
const test_router = require('./router/test_router');
const projects_router = require('./router/projects_router');
const users_router = require('./router/users_router');
const site_router = require('./router/site_router');
const admin_router = require('./router/admin_router');

const { MyEvent } = require('./models/myevent');

const telegrambot = require('./telegram/telegrambot');

require('./db/mongoose');

console.log("DB: " + process.env.DATABASE);
console.log("PORT: " + port);
console.log("MONGODB_URI: " + process.env.MONGODB_URI);

var app = express();

const tools = require('./tools/general');


var mongoose = require('mongoose');
const cfgserver = mongoose.model('cfgserver');
const { ObjectID } = require('mongodb');

app.use(express.static('views'));

// app.use(express.static(path.join(__dirname, 'client')));

app.use(bodyParser.json());

// app.set('view engine', 'pug');

// Set static folder
// app.use(express.static(path.join(__dirname, 'public')));


i18n.configure({
  locales: ['it', 'enUs', 'es', 'fr', 'pt', 'si'],
  // cookie: 'cook',
  directory: __dirname + '/locales'
});

app.use(cors({
  exposedHeaders: ['x-auth'],
}));

app.use(bodyParser.json());

// app.use(express.cookieParser());
app.use(i18n.init);


// Use Routes
app.use('/', index_router);
app.use('/subscribe', subscribe_router);
app.use('/sendmsg', sendmsg_router);
app.use('/push', push_router);
app.use('/news', newsletter_router);
app.use('/booking', booking_router);
app.use('/dashboard', dashboard_router);
app.use('/event', myevent_router);
app.use('/email', email_router);
app.use('/todos', todos_router);
app.use('/test', test_router);
app.use('/projects', projects_router);
app.use('/users', users_router);
app.use('/site', site_router);
app.use('/admin', admin_router);

// catch 404 and forward to error handler
// app.use(function (req, res, next) {
//   var err = new Error('Not Found');
//   err.status = 404;
//   next(err);
// });

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

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {

  app.use(function (err, req, res, next) {
    console.log('Error: ', err.message);
    // console.trace();
    res.status(err.status || 500).send({ error: err.message });
    // res.render('error', {
    //   message: err.message,
    //   error: err
    // });
  });

}

require('./telegram/telegrambot');


// *** DB CONNECTIONS ***
// mysql_func.mySqlConn_Shen.connect((err) => {
//   if (!err)
//     console.log('DB connection to Shen Database succeded.');
//   else
//     console.log('DB connection to Shen Database FAILED \n Error: ' + JSON.stringify(err, undefined, 2));
// });


if ((process.env.NODE_ENV === 'production') || (process.env.NODE_ENV === 'test')) {
  var httpsServer = https.createServer(credentials, app);
  console.log("httpsServer: port ", port);
  httpsServer.listen(port);
} else {
  console.log("httpServer: port ", port);
  var httpServer = http.createServer(app);
  httpServer.listen(port);
}

// app.use(throttle(1024 * 128)); // throttling bandwidth

// app.use((req, res, next) => {
//   res.header('Access-Control-Allow-Origin', '*')
//   res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
//   next()
// });

if (process.env.PROD !== 1) {
  testmsgwebpush();
  // sendemail.testemail('2', 'it');

  let miapass = '';

  if (miapass !== '') {
    let crypt = tools.cryptdata(miapass);
    let decrypt = tools.decryptdata(crypt);

    console.log('crypted:', crypt);
    console.log('decrypted:', decrypt);
  }

  mycron();
}

// ----------------- MAILCHIMP -----
const querystring = require('querystring');
const mailchimpClientId = 'xxxxxxxxxxxxxxxx';

app.get('/mailchimp/auth/authorize', function (req, res) {
  res.redirect('https://login.mailchimp.com/oauth2/authorize?' +
    querystring.stringify({
      'response_type': 'code',
      'client_id': mailchimpClientId,
      'redirect_uri': 'http://127.0.0.1:3000/mailchimp/auth/callback'
    }));
});

// -----------------


startserv();


function populateDBadmin() {
  const cfgserv = [{
    _id: new ObjectID(),
    idapp: '9',
    chiave: 'vers',
    userId: 'ALL',
    valore: '0.1.2'
  }];

  let cfg = new cfgserver(cfgserv[0]).save();
}

function startserv() {

  // populateDBadmin();

  // Check if is Empty (new Server Data)
  /*
    cfgserver.countDocuments(function (err, count) {
      if (!err && count === 0) {
        populateDBadmin();
      }
    });
  */

}


function mycron() {
  for (const app of MYAPPS) {
    sendemail.checkifPendingNewsletter(app.idapp);
    sendemail.checkifSentNewsletter(app.idapp);
  }
}

function testmsgwebpush() {
  var { User } = require('./models/user');

  // console.log('nomeapp 1: ' , tools.getNomeAppByIdApp(1));
  // console.log('nomeapp 2: ' , tools.getNomeAppByIdApp(2));

  User.find({ username: 'paoloar77' }).then((arrusers) => {
    if (arrusers !== null) {
      for (const user of arrusers) {
        tools.sendNotificationToUser(user._id, 'Server', 'Il Server è Ripartito', '/', '', 'server', [])
          .then(ris => {
            if (ris) {

            } else {
              // already sent the error on calling sendNotificationToUser
            }
          })
      }
    }
  });

}

// Cron every X minutes
cron.schedule('*/2 * * * *', () => {
  // console.log('Running Cron Job');
  mycron();
});

async function resetProcessingJob() {

  arrrec = await Newstosent.find({});

  for (const rec of arrrec) {
    rec.processing_job = false;
    await Newstosent.findOneAndUpdate({ _id: rec.id }, { $set: rec }, { new: false }).then((item) => {

    });
  }
}

//app.listen(port, () => {
//  console.log(`Server started at port ${port}`);
//});

async function inizia() {
  if (process.env.NODE_ENV === 'production') {
    await telegrambot.sendMsgTelegram(tools.AYNI, telegrambot.ADMIN_USER_SERVER, `Ciao ${telegrambot.ADMIN_USER_NAME_SERVER}!`);
    await telegrambot.sendMsgTelegramByIdTelegram(tools.AYNI, telegrambot.ADMIN_IDTELEGRAM_SERVER, `Il Server ${process.env.DATABASE} è appena ripartito!`);

    await telegrambot.sendMsgTelegramByIdTelegram('2', telegrambot.ADMIN_IDTELEGRAM_SERVER, `Il Server ${process.env.DATABASE} è appena ripartito!`);

    testo = 'Ciao Paolo!';
    myid = await telegrambot.sendMsgTelegramByIdTelegram(tools.AYNI, telegrambot.ADMIN_IDTELEGRAM_SERVER, testo);

  }
  // testo = 'testo modificato';
  // myid = await telegrambot.sendMsgTelegramByIdTelegram('7', telegrambot.ADMIN_IDTELEGRAM_SERVER, testo, myid, telegrambot.ADMIN_IDTELEGRAM_SERVER);

}

inizia();

resetProcessingJob();


//


// telegrambot.sendMsgTelegramToTheManagers('7', 'PROVAAA!');

// if (process.env.PROD !== 1) {
//   const reg = require('./reg/registration');
//   const link = reg.getlinkregByEmail('7', 'tomasihelen@dasdasgmail.comAAAA' , 'HelenTomasidasdasd');
//   const link2 = reg.getlinkregByEmail('7', 'tomasihelen@gmail.com' , 'HelenTomasi');
//   //const link2 = reg.getlinkregByEmail('7', 'elenaliubicich@gmail.com' , 'Elenaliu');
//
//   console.log(link);
//   console.log(link2);
// }

module.exports = { app };
