const _        = require('lodash');
const electron = require('electron');
const logger   = require('./logger');

const BrowserWindow = electron.BrowserWindow;



function MainWindow(options) {
    this.window = null;
    this.options = options;
}

MainWindow.prototype.create = function (args) {
    var self = this;
    if (this.window) {
        return;
    }

    // Create the browser window.
    this.window = new BrowserWindow(self.options.browserOptions);
    this.window.loadURL(self.options.url);

    if(self.options.clearCache){
        this.window.webContents.session.clearCache(function(){ });
    }

    if (self.options.openDevTools) {
        this.window.webContents.openDevTools();
    }

    this.window.on('closed', function() {
        self.window = null;

        if (args && args.onCloseCallBack) { args.onCloseCallBack(); }
    });
};

MainWindow.prototype.executeJavaScript = function(cmd) {
    if (!this.window) {
        return;
    }

    this.window.webContents.executeJavaScript(cmd);
};

MainWindow.prototype.propagateJavaScript = function(cmd) {
    if (!this.window) {
        return;
    }

    this.window.webContents.send('javascriptCmd', cmd);
};

MainWindow.prototype.focus = function() {
    if (this.window) {
        this.window.focus();
    }
};

MainWindow.prototype.clearCache = function() {
    if (this.window) {
        var session = this.window.webContents.session;

        // Clear html cache
        session.clearCache(() => { });

        // Clear cookies cache
        session.cookies.get({}, (error, cookies) => {
            _.forEach(cookies, (cookie) => {
                logger.info('==> clear cookie ' + cookie.name);
                session.cookies.remove('http://' + cookie.domain, cookie.name, () => {});
            });
        });
    }
}

module.exports = MainWindow;