const { app, BrowserWindow } = require('electron')
const protocol = require('electron').protocol
const path = require('path')
const ipcMessages = require(path.join(__dirname, '/src/defaults/ipc-messages'))
const { autoUpdater } = require('electron-updater')
const fs = require('fs')
const { AdBlockClient, FilterOptions } = require('ad-block')

const windowDataPath = path.join(app.getPath('userData'), "window-data.json");

const protocolName = 'wexond'

let mainWindow

let windowBounds = {}

/** Global events. */

app.on('ready', () =>  {
  if (process.env.NODE_ENV !== 'dev') autoUpdater.checkForUpdates()
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow == null) {
    createWindow()
  }
})

process.on('uncaughtException', (error) => {
  console.log(error)
})

autoUpdater.on('checking-for-update', () => {})
autoUpdater.on('update-available', (info) => {})
autoUpdater.on('update-not-available', (info) => {})
autoUpdater.on('error', (err) => {})
autoUpdater.on('download-progress', (progressObj) => {})

autoUpdater.on('update-downloaded', (info) => {
  autoUpdater.quitAndInstall()
})

const createWindow = () => {
  let data = null
  try {
    data = fs.readFileSync(windowDataPath)
    data = JSON.parse(data)
  } catch (e) {
    console.error(e)
  }

  const windowData = {
    frame: false,
    minWidth: 300,
    minHeight: 430,
    width: 900,
    height: 700,
    show: false,
    titleBarStyle: 'hidden-inset'
  }

  if (data != null && data.bounds != null) {
    Object.assign(windowData, data.bounds)
  }

  mainWindow = new BrowserWindow(windowData)
  mainWindow.loadURL(path.join('file://', __dirname, '/public/app/index.html'))
  mainWindow.setMenu(null)

  windowBounds = mainWindow.getBounds()

  mainWindow.on('resize', () => {
    if (!mainWindow.isMaximized()) {
      windowBounds = mainWindow.getBounds()
    }
  })

  mainWindow.on('move', () => {
    if (!mainWindow.isMaximized()) {
      windowBounds = mainWindow.getBounds()
    }
  })

  if (data != null && data.maximized) {
    mainWindow.maximize()
  }

  mainWindow.on('closed', () => {
    mainWindow = null
  })

  mainWindow.on('close', () => {
    data = {
      maximized: mainWindow.isMaximized(),
      bounds: windowBounds
    }

    fs.writeFileSync(windowDataPath, JSON.stringify(data))
  })

  mainWindow.on('unresponsive', () => {})

  mainWindow.on('app-command', function (e, cmd) {
    switch (cmd) {
      case 'browser-backward':
        mainWindow.webContents.send(ipcMessages.BROWSER_GO_BACK)
        return
      case 'browser-forward':
        mainWindow.webContents.send(ipcMessages.BROWSER_GO_FORWARD)
        return
    }
  })

  mainWindow.once('ready-to-show', () => {
    mainWindow.show()

    const client = new AdBlockClient()

    fs.readFile(path.join(__dirname, 'resources/adblock/adblock.dat'), (err, data) => {
      if (err) return console.error(err)

      client.deserialize(data)

      mainWindow.webContents.session.webRequest.onBeforeRequest((details, callback) => {

        if (details.url.startsWith('http://') || details.url.startsWith('https://')) {
          const isAd = client.matches(details.url, FilterOptions.noFilterOption)

          if (isAd) {
            return callback({
              cancel: true,
              requestHeaders: details.requestHeaders
            })
          }
        }
       
        return callback({
          cancel: false,
          requestHeaders: details.requestHeaders
        })
      })
    })
  })

  if (process.env.NODE_ENV === 'dev') {
    mainWindow.webContents.openDevTools({mode: 'detach'})
  }
}

protocol.registerStandardSchemes([protocolName])
app.on('ready', function () {
  protocol.registerFileProtocol(protocolName, (request, callback) => {
    let url = request.url.substr(protocolName.length + 3)
    let lastChar = url.substr(url.length - 1)

    if (lastChar === '/') {
      url += 'index.html'
    }

    let data = path.join(__dirname, '/public/', url)

    callback(data)
  }, (error) => {
    if (error) {
      console.error('Failed to register protocol ' + protocolName + '://')
    }
  })
  createWindow()
})

@@ -2738,74 +2738,76 @@
 %0A%0A  
-mainWindow.once('ready-to-show', () =%3E %7B%0A    mainWindow.show(
+console.log(path.join(__dirname, 'resources/adblock/adblock.dat')
 )%0A%0A
-  
   co
@@ -2840,18 +2840,16 @@
 ient()%0A%0A
-  
   fs.rea
@@ -2926,26 +2926,24 @@
 a) =%3E %7B%0A    
-  
 if (err) ret
@@ -2970,18 +2970,16 @@
 r)%0A%0A    
-  
 client.d
@@ -2996,18 +2996,16 @@
 (data)%0A%0A
-  
     main
@@ -3086,26 +3086,24 @@
 =%3E %7B%0A%0A      
- 
- 
 if (details.
@@ -3165,26 +3165,24 @@
 tps://')) %7B%0A
-  
         cons
@@ -3253,26 +3253,24 @@
 n)%0A%0A        
-  
 if (isAd) %7B%0A
@@ -3275,26 +3275,24 @@
 %7B%0A          
- 
- 
 return callb
@@ -3301,34 +3301,32 @@
 k(%7B%0A            
-  
 cancel: true,%0A  
@@ -3323,18 +3323,16 @@
 : true,%0A
-  
         
@@ -3380,31 +3380,27 @@
 s%0A          
- 
- 
 %7D)%0A
-  
         %7D%0A  
@@ -3403,26 +3403,24 @@
 %7D%0A      
-  
 %7D%0A      
  %0A      
@@ -3415,18 +3415,15 @@
     
- 
 %0A      
-  
 retu
@@ -3436,34 +3436,32 @@
 lback(%7B%0A        
-  
 cancel: false,%0A 
@@ -3459,18 +3459,16 @@
  false,%0A
-  
         
@@ -3506,24 +3506,29 @@
 Headers%0A    
+  %7D)%0A
     %7D)%0A     
@@ -3524,28 +3524,83 @@
    %7D)%0A  
-    %7D)%0A    %7D
+%7D)%0A%0A  mainWindow.once('ready-to-show', () =%3E %7B%0A    mainWindow.show(
 )%0A  %7D)%0A%0A

Fix adblock loading