const {app, BrowserWindow, ipcMain, dialog} = require("electron");
const path = require("path");
const electronIpcMain = require('electron').ipcMain;
const electronDialog = require('electron').dialog;
const FtpSrv = require('ftp-srv');
const errors = require('ftp-srv').ftpErrors;

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
// eslint-disable-next-line global-require
if (require('electron-squirrel-startup')) {
  app.quit();
}

let mainWindow;
let ftpDir; 

const createWindow = () => {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 800,
    height: 900,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
    },
  });
  mainWindow.loadFile(path.join(__dirname, 'index.html'));

  // Open the DevTools.
  //mainWindow.webContents.openDevTools();
};

app.on('ready', createWindow);
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});
app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

/// IPC handlers for operations that should be executed on main thread

electronIpcMain.handle('chooseFtpDirectory', () => {
  return electronDialog.showOpenDialog(mainWindow, {properties: ['openDirectory']})
  .then((result) => {
    if (result.canceled) { return }
    ftpDir = result.filePaths[0]
    setupFtpServer(ftpDir);
    mainWindow.webContents.send('handleLg', `Uruchamiam serwer FTP na katalogu: ${ftpDir}`);
    return ftpDir;
  })
})

//// Setting up FTP Server

const setupFtpServer = (dir) => {
  const port=21;
  const ftpServer = new FtpSrv({
      url: "ftp://0.0.0.0:" + port,
      anonymous: true
  });

  ftpServer.on('login', ({ connection, username, password }, resolve, reject) => { 
    mainWindow.webContents.send('handleLg', `Uzytkownik ${username} probuje sie zalogowac`);
    if(username === 'kserotech' && password === 'kserotech'){
        mainWindow.webContents.send('handleLg', `<span style="color: green">Uzytkownik ${username} pomyslnie zalogowal sie</span>`);

        connection.on('STOR', (error, fileName) => { 
          if(error) { mainWindow.webContents.send('handleLg', `<span style="color: red">Blad: ${error}</span>`); }
          mainWindow.webContents.send('handleLg', `<span style="color: green">Plik ${fileName} zostal odebrany</span>`);
        });
    
        return resolve({ root:dir });    
    }
    mainWindow.webContents.send('handleLg', `<span style="color: red">Blad: uzytkownik ${username} z haslem ${password} nie zalogowal sie, upewnij sie ze maszyna kliencka zostala skonfigurowana z odpowiednim adresem IP (powyzej) oraz uzytkownikiem: kserotech i haslem: kserotech</span>`);
  
    return reject(new errors.GeneralError('Niepoprawne haslo, powinno byc uzytkownik: kserotech, haslo: kserotech', 401));
  });

  ftpServer.on('server-error', ({error}) => { mainWindow.webContents.send('handleLg', `<span style="color: red">Blad: ${error}</span>`); });

  ftpServer.listen().then(() => { 
    console.log('Ftp server is starting...')
  });
}