const {app, dialog, BrowserWindow, ipcMain, Menu, MenuItem} = require("electron")
const path = require("path")
const url = require("url")
const fs = require("fs");
const menu = new Menu()
const imdbMain = "http://www.imdb.com"
const imdbRandom = "http://www.imdb.com/random/title"

var packageJSON = JSON.parse(fs.readFileSync(path.join(__dirname, "package.json"), "utf8"));
var count = -1
var game = false
var title = ""
var titleID = ""
var currentURL = ""

let menuWindow
let hiddenWindow
let gameWindow
let searchWindow

function urlCheck(sourceURL) {
    if (sourceURL.indexOf("ref_=nv_sr") != -1) {
        return false
    }

    if (sourceURL.search(/^((http|https):\/\/).\w+.imdb.com/g) == -1) {
        return false
    }

    return true
}

function createWindow () {
    menuWindow = new BrowserWindow({title: "Menu", width: 220, height: 450, resizable: false})
    hiddenWindow = new BrowserWindow({parent: menuWindow, show: false})
    gameWindow = new BrowserWindow({parent: menuWindow, title: packageJSON.description, width: 900, height: 600, show: false})
    searchWindow = new BrowserWindow({parent: menuWindow, title: "Find in page", width: 320, height: 80, resizable: false, show: false})
    //menuWindow.webContents.openDevTools()
    
    menuWindow.loadURL(url.format({
        pathname: path.join(__dirname, "index.html"),
        protocol: "file:",
        slashes: true
    }))

    hiddenWindow.webContents.on("did-start-loading", function (event) {
        console.log("Loading....")
    })

    hiddenWindow.webContents.on("did-finish-load", function (event) {
        title = hiddenWindow.webContents.getTitle().replace(" - IMDb", "")
        titleID = hiddenWindow.webContents.getURL().replace(imdbMain, "")
        console.log(title)
        console.log(titleID)

        menuWindow.webContents.send("title", title)

        hiddenWindow.webContents.executeJavaScript(
        "document.querySelector(\"div.poster a img\").getAttribute(\"src\")",
        true)
        .then((posterURL) => {
            menuWindow.webContents.send("posterURL", posterURL)
        })

        hiddenWindow.webContents.executeJavaScript(
        "document.querySelector(\"div.poster a\").getAttribute(\"href\")",
        true)
        .then((posterLink) => {
            menuWindow.webContents.send("posterLargeURL", imdbMain + posterLink)
        })

        count = -1
        game = true
        gameWindow.webContents.session.clearStorageData()
        gameWindow.loadURL(imdbMain)
        menuWindow.webContents.send("unlock", null)
    })

    gameWindow.on("page-title-updated", function (event) {
        event.preventDefault()
        gameWindow.webContents.stopFindInPage("clearSelection")

        if (!gameWindow.isVisible()) {
            gameWindow.show()
        }

        currentURL = gameWindow.webContents.getURL()
        console.log(currentURL)

        if (game == true) {
            count = count + 1
            menuWindow.webContents.send("count", count)

            if (!urlCheck(currentURL)) {
                game = false
                dialog.showMessageBox({
                title: "Message",
                message: "You can not do this.", 
                buttons: ["OK"]})
            }

            else if (currentURL.indexOf(titleID) != -1) {
                game = false
                console.log("(" + count + ")Found!")

                dialog.showMessageBox({
                title: "Message",
                message: "Congratulations, you have found the correct title.", 
                buttons: ["OK"]})
            }
        }
        else {
            dialog.showMessageBox({
            title: "Message",
            message: "Please start a new game.", 
            buttons: ["OK"]})
        }
    })

    searchWindow.loadURL(url.format({
        pathname: path.join(__dirname, "search.html"),
        protocol: "file:",
        slashes: true
    }))

    ipcMain.on("newGame", (event) => {
        console.log("New Game")
        menuWindow.webContents.send("posterDisabled", null)
        hiddenWindow.loadURL(imdbRandom)
    })

    ipcMain.on("about", (event) => {
        dialog.showMessageBox({
        title: "About",
        message: packageJSON.description + "\nAuthor: " + packageJSON.author + "\nLicense: " + packageJSON.license 
        + "\nVersion: " + packageJSON.version + "\nElectron: " + process.versions.electron + "\nChrome: " + process.versions.chrome, 
        buttons: ["OK"]})
    })

    ipcMain.on("search", (event, keyword) => {
        if (keyword) {
            gameWindow.webContents.findInPage(keyword)
        }
        else {
            gameWindow.webContents.stopFindInPage("clearSelection")
        }
    })

    gameWindow.on("close", function (event) {
      event.preventDefault()
      gameWindow.hide()
      searchWindow.hide()
    })

    searchWindow.on("close", function (event) {
      event.preventDefault()
      searchWindow.hide()
    })

    menuWindow.on("closed", function () {
        menuWindow = null
        hiddenWindow = null
        gameWindow = null
        searchWindow = null
    })

    menu.append(new MenuItem({
        accelerator: "CmdOrCtrl+F",
        click: () => {
            searchWindow.show()
        }
    }))

    Menu.setApplicationMenu(menu)
}

app.on("ready", createWindow)

app.on("browser-window-created", function (event, window) {
    window.setAutoHideMenuBar(true)
    window.setMenuBarVisibility(false)

    window.webContents.on("will-navigate", function (event) {
        if (window.getTitle().indexOf(packageJSON.description) == -1 && window.webContents.getURL().indexOf("mediaviewer") != -1) {
            event.preventDefault()
        }
    })
})

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

app.on("activate", function () {
    if (menuWindow === null) {
        createWindow()
    }
})
