import 'zone.js/node';

import { APP_BASE_HREF } from '@angular/common';
import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import * as compression from 'compression';
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { AppServerModule } from './src/main.server';
import {REQUEST, RESPONSE} from "./src/app/openaireLibrary/utils/tokens";
var bodyParser = require('body-parser')
var jsonParser = bodyParser.json()
import * as fs from 'fs';
import {readFileSync} from "fs";
import {properties} from "./src/environments/environment";
import axios, {AxiosHeaders} from "axios";
import {CacheIndicators} from "./src/app/openaireLibrary/monitor-admin/utils/cache-indicators/cache-indicators";
import {UserManagementService} from "./src/app/openaireLibrary/services/user-management.service";
import {Session, User} from "./src/app/openaireLibrary/login/utils/helper.class";
import {Stakeholder} from "./src/app/openaireLibrary/monitor/entities/stakeholder";
// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
  const server = express();
  server.use(compression());
  const distFolder = join(process.cwd(), 'dist/irish-monitor/browser');
  const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';
  let cacheIndicators: CacheIndicators = new CacheIndicators();

  // Our Universal express-engine (found @ https://github.com/angular/universal/tree/main/modules/express-engine)
  server.engine('html', ngExpressEngine({
    bootstrap: AppServerModule,
    inlineCriticalCss: false
  }));

  server.set('view engine', 'html');
  server.set('views', distFolder);

  // Example Express Rest API endpoints
  // server.get('/api/**', (req, res) => { });
  // Serve static files from /browser
  server.get('/webstats/:year/:month', (req, res) => {
    let today = new Date();
    let filename = "oamonitor-"+ req.params['year']+ "-" + req.params['month'] ;
    res.setHeader('content-disposition','attachment; filename='+'webstats-'+ req.params['year']+ '_' + req.params['month']+'.json');
    let file = " ";
    try {
      file = readFileSync(properties.matomoLogFilesPath + filename +".json", 'utf-8');
    }catch (e){}
    res.status(200).send( file);
  });
  server.get('/public-logs/:year/:month', (req, res) => {
    let today = new Date();
    let filename = getFileName(req.params['year'], req.params['month'])
    res.setHeader('content-disposition','attachment; filename='+filename);
    let file = " ";
    try {
      file = readFileSync(properties.logFilesPath + filename, 'utf-8');
    }catch (e){}
    res.status(200).send( file);
  });
  server.post('/logAction',  jsonParser,(req, res) => {
    let log = req.body;
    log.date = new Date();
    let filename = getFileName(log.date.getFullYear(), log.date.getMonth()+1);
    fs.appendFile(properties.logFilesPath + filename, formatPrettyLog(log)+ "\n", 'utf8', function(err) {
      if (err) {
        console.error(err);
        return console.error(err);
      }
    });
    res.status(200).send({
      code: 200,
      message: 'action received!'
    });
  });

  server.post('/cache/:alias', jsonParser, async (req, res) => {
    await checkPermissions(req, res, (stakeholder, user) => {
      if (cacheIndicators.completed(stakeholder._id)) {
        res.send({
          id: stakeholder._id,
          report: cacheIndicators.createReport(stakeholder._id, cacheIndicators.stakeholderToCacheItems(stakeholder), stakeholder.name, user.email)
        });
      } else {
        res.status(409).send('There is another active caching process for this stakeholder');
      }
    });
  });

  server.get('/cache/:alias', async (req, res) => {
    await checkPermissions(req, res, stakeholder => {
      if (cacheIndicators.exists(stakeholder._id)) {
        res.send({
          id: stakeholder._id,
          report: cacheIndicators.getReport(stakeholder._id)
        });
      } else {
        res.status(404).send('There is not an active caching process for this stakeholder');
      }
    });
  });

  async function checkPermissions(req, res, access: (stakeholder, user) => void) {
    let headers: AxiosHeaders = new AxiosHeaders();
    headers.set('Cookie', req.headers.cookie);
    let userinfoRes = (await axios.get<any>(UserManagementService.userInfoUrl(), {
      withCredentials: true,
      headers: headers
    }).catch(error => {
      return error.response;
    }));
    if (userinfoRes.status === 200) {
      let user = new User(userinfoRes.data);
      let stakeholderRes = (await axios.get<Stakeholder>(properties.monitorServiceAPIURL + '/stakeholder/' + encodeURIComponent(req.params.alias), {
        withCredentials: true,
        headers: headers
      }).catch(error => {
        return error.response;
      }));
      if (stakeholderRes.status === 200) {
        let stakeholder = stakeholderRes.data;
        if (Session.isPortalAdministrator(user) || Session.isCurator(stakeholder.type, user)) {
          access(stakeholder, user);
        } else {
          res.status(403).send('You are forbidden to access this resource');
        }
      } else {
        res.status(stakeholderRes.status).send(stakeholderRes.statusText);
      }
    } else {
      res.status(userinfoRes.status).send(userinfoRes.data.message);
    }
  }

  server.get('*.*', express.static(distFolder, {
    maxAge: '1y'
  }));

  // All regular routes use the Universal engine
  server.get('*', (req, res) => {
    res.render(indexHtml, {
          req, providers: [
            {
              provide: APP_BASE_HREF,
              useValue: req.baseUrl
            },
            {
              provide: REQUEST, useValue: (req)
            },
            {
              provide: RESPONSE, useValue: (res)
            }
          ]
        }
    );
  });


  return server;
}

function run(): void {
  const port = process.env['PORT'] || 4000;

  // Start up the Node server
  const server = app();
  server.listen(port, () => {
    console.log(`Node Express server listening on http://localhost:${port}`);
  });
}

function getFileName(year, month){
  return 'actions' + (year && month ? "_" + year + "_" + month : "")+".log";
}
function formatPrettyLog(log){
  return "On " + (log.date ? formatDateAndTime(log.date) : "") + " "  /*+ logs[i].action + " "*/ + log.message;
}
function formatDateAndTime(dateStr){
  let date = new Date(dateStr);
  const formatter = new Intl.DateTimeFormat('en-GB', {

    timeStyle: 'short',
    timeZone: 'GMT',
  });
  return date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear() + " "
    + formatter.format(date) + "";

}

// Webpack will replace 'require' with '__webpack_require__'
// '__non_webpack_require__' is a proxy to Node 'require'
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = mainModule && mainModule.filename || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
  run();
}

export * from './src/main.server';
