"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var path = require("path");
var fs = require("fs");
var os_1 = require("os");
var electron_1 = require("electron");
var encoding = require("encoding-japanese");
var config = electron_1.remote.getGlobal('config');
var home_dir = config.hide_title_bar ? '' : os_1.homedir();
var on_darwin = process.platform === 'darwin';
function noop() {
}
var watching_path = electron_1.remote.require('./initial_path.js')(config.default_watch_path || '');
var onPathButtonPushed = noop;
var onSearchButtonPushed = noop;
var onTOCButtonPushed = noop;
function getMainDrawerPanel() {
    return document.getElementById('main-drawer');
}
function onPrintButtonPushed() {
    electron_1.remote.getCurrentWindow().webContents.print();
}
function getLintArea() {
    return document.getElementById('lint-area');
}
function make_title(p) {
    if (!p || config.hide_title_bar) {
        return 'Shiba';
    }
    if (p.startsWith(home_dir)) {
        return make_title("~" + p.slice(home_dir.length));
    }
    return "Shiba (" + p + ")";
}
function getScroller() {
    var selected = getMainDrawerPanel().selected;
    if (selected === null) {
        return null;
    }
    if (selected === 'drawer') {
        var panel = document.querySelector('paper-header-panel[drawer]');
        return panel.scroller;
    }
    else {
        return document.getElementById('viewer-wrapper');
    }
}
function scrollContentBy(x, y) {
    var scroller = getScroller();
    if (!scroller) {
        return;
    }
    if (x !== 0) {
        scroller.scrollLeft += x;
    }
    if (y !== 0) {
        scroller.scrollTop += y;
    }
}
function setChildToViewerWrapper(new_child) {
    var target = document.getElementById('viewer-wrapper');
    if (target.hasChildNodes()) {
        target.replaceChild(new_child, target.firstChild);
    }
    else {
        target.appendChild(new_child);
    }
}
function openMarkdownDoc(file_path, modifier_key) {
    electron_1.ipcRenderer.send('shiba:notify-path', file_path);
    if (modifier_key) {
        document.title = make_title(file_path);
        watching_path = file_path;
    }
}
function renderMarkdownPreview(file) {
    var exts = config.file_ext.markdown;
    var font_size = config.markdown.font_size;
    var isGitHubStyle = config.markdown.css_path.endsWith('/github-markdown.css');
    fs.readFile(file, null, function (err, bytes) {
        if (err) {
            console.error(err);
            return;
        }
        var enc = encoding.detect(bytes);
        var markdown = !enc || enc === 'UTF8' || enc === 'ASCII' || enc === 'BINARY' || enc === 'UTF32'
            ? bytes.toString()
            : new Buffer(encoding.convert(bytes, 'UTF8', enc)).toString();
        var markdown_preview = document.getElementById('current-markdown-preview');
        if (markdown_preview !== null) {
            markdown_preview.document = markdown;
            return;
        }
        markdown_preview = document.createElement('markdown-preview');
        markdown_preview.id = 'current-markdown-preview';
        if (font_size !== '') {
            markdown_preview.fontSize = font_size;
        }
        if (!isGitHubStyle) {
            markdown_preview.isGithubStyle = false;
        }
        markdown_preview.exts = exts;
        markdown_preview.openMarkdownDoc = openMarkdownDoc;
        markdown_preview.onDocumentUpdated = function () { return getLintArea().showLintResult(); };
        markdown_preview.onSanitizationError = function (message, reason) {
            console.log(message, reason);
            getLintArea().sanitize_error = {
                header: message,
                body: reason,
            };
        };
        setChildToViewerWrapper(markdown_preview);
        getLintArea().sanitize_error = null;
        markdown_preview.document = markdown;
    });
    var lint = getLintArea();
    lint.already_previewed = false;
    lint.messages = undefined;
}
function renderHtmlPreview(file) {
    var html_preview = document.getElementById('current-html-preview');
    if (html_preview !== null) {
        html_preview.src = 'file://' + file;
        return;
    }
    html_preview = document.createElement('iframe');
    html_preview.id = 'current-html-preview';
    html_preview.className = 'current-html-preview';
    html_preview.onload = function (_) {
        html_preview.setAttribute('height', html_preview.contentWindow.document.body.scrollHeight + 'px');
    };
    html_preview.setAttribute('seamless', '');
    html_preview.setAttribute('sandbox', 'allow-same-origin allow-top-navigation allow-forms allow-scripts');
    html_preview.setAttribute('height', window.innerHeight + 'px');
    html_preview.src = 'file://' + file;
    setChildToViewerWrapper(html_preview);
}
function getDialogDefaultPath() {
    try {
        var stats = fs.lstatSync(watching_path);
        if (stats.isDirectory()) {
            return watching_path;
        }
        return path.dirname(watching_path);
    }
    catch (e) {
        return '';
    }
}
function prepareMarkdownStyle(markdown_config) {
    var css_path = markdown_config.css_path, code_theme = markdown_config.code_theme;
    var markdown_css_link = document.createElement('link');
    markdown_css_link.rel = 'stylesheet';
    markdown_css_link.href = css_path;
    document.head.appendChild(markdown_css_link);
    if (code_theme === '') {
        return;
    }
    var code_theme_css_link = document.createElement('link');
    code_theme_css_link.rel = 'stylesheet';
    code_theme_css_link.href = "../../node_modules/highlight.js/styles/" + code_theme + ".css";
    document.head.appendChild(code_theme_css_link);
    if (code_theme !== 'github' && css_path.endsWith('/github-markdown.css')) {
        console.warn('github-markdown.css overrides background color of code block.');
    }
}
function reloadPreview() {
    if (document.getElementById('current-markdown-preview') !== null) {
        renderMarkdownPreview(watching_path);
    }
    else if (document.getElementById('current-html-preview') !== null) {
        renderHtmlPreview(watching_path);
    }
    else {
        return;
    }
    document.getElementById('reload-button').classList.add('rotate');
}
function shouldWatch(file) {
    var ext = path.extname(file).substr(1);
    for (var _i = 0, _a = Object.keys(config.file_ext); _i < _a.length; _i++) {
        var kind = _a[_i];
        var exts = config.file_ext[kind];
        if (exts.indexOf(ext) !== -1) {
            return true;
        }
    }
    return false;
}
(function () {
    var lint = getLintArea();
    if (config.voice.enabled) {
        lint.voice_src = config.voice.source;
    }
    if (config.hide_title_bar) {
        lint.enable_inset = config.hide_title_bar;
    }
    prepareMarkdownStyle(config.markdown);
    function chooseFileOrDirWithDialog() {
        var filters = [
            {
                name: 'Markdown',
                extensions: config.file_ext.markdown,
            },
            {
                name: 'HTML',
                extensions: config.file_ext.html,
            },
        ];
        var properties = ['openFile'];
        if (on_darwin) {
            properties.push('openDirectory');
        }
        var paths = electron_1.remote.dialog.showOpenDialog({
            title: 'Choose file or directory to watch',
            defaultPath: getDialogDefaultPath(),
            filters: filters,
            properties: properties,
        });
        if (!paths || paths.length === 0) {
            return '';
        }
        return paths[0];
    }
    electron_1.ipcRenderer.on('shiba:notify-content-updated', function (_, kind, file) {
        var button = document.getElementById('reload-button');
        button.classList.add('rotate');
        var base = document.querySelector('base');
        base.setAttribute('href', 'file://' + path.dirname(file) + path.sep);
        switch (kind) {
            case 'markdown': {
                renderMarkdownPreview(file);
                break;
            }
            case 'html': {
                renderHtmlPreview(file);
                break;
            }
            default:
                break;
        }
    });
    electron_1.ipcRenderer.on('shiba:notify-linter-result', function (_, messages) {
        lint.messages = messages;
        var button = document.getElementById('lint-button');
        if (messages.length === 0) {
            button.style.color = '#d99e5f';
        }
        else {
            button.style.color = '#ce3c4a';
        }
    });
    electron_1.ipcRenderer.on('return-lint-url', function (_, url) {
        lint.lint_url = url;
    });
    onPathButtonPushed = function () {
        var chosen = chooseFileOrDirWithDialog();
        if (chosen === '') {
            return;
        }
        watching_path = chosen;
        document.title = make_title(watching_path);
        electron_1.ipcRenderer.send('shiba:notify-path', watching_path);
    };
    if (watching_path === '') {
        onPathButtonPushed();
    }
    else {
        electron_1.ipcRenderer.send('shiba:notify-path', watching_path);
        document.title = make_title(watching_path);
    }
    var searcher = document.getElementById('builtin-page-searcher');
    onSearchButtonPushed = function () {
        searcher.toggle();
    };
    var toc = document.getElementById('table-of-contents');
    onTOCButtonPushed = function () {
        var preview = document.getElementById('current-markdown-preview');
        if (preview === null) {
            return;
        }
        toc.toggle(preview.currentOutline);
    };
    toc.scrollCallback = function (h) {
        var preview = document.getElementById('current-markdown-preview');
        if (preview !== null) {
            preview.scrollToHeading(getScroller(), h);
        }
    };
    var cancel_event = function (e) {
        e.preventDefault();
    };
    document.body.addEventListener('dragenter', cancel_event);
    document.body.addEventListener('dragover', cancel_event);
    document.body.addEventListener('drop', function (event) {
        event.preventDefault();
        var files = event.dataTransfer.files;
        if (files.length === 0) {
            return;
        }
        var p = files[0].path;
        if (!p) {
            console.log('Failed to get the path of dropped file');
            return;
        }
        if (!shouldWatch(p)) {
            console.log("Unknown kind of file (checking file extensions), iginored: " + p);
            return;
        }
        watching_path = p;
        electron_1.ipcRenderer.send('shiba:notify-path', p);
        document.title = make_title(p);
    });
    var chooser = document.querySelector('paw-filechooser');
    chooser.onFileChosen = function (file) {
        watching_path = file;
        electron_1.ipcRenderer.send('shiba:notify-path', file);
        document.title = make_title(file);
    };
    var reload_button = document.getElementById('reload-button');
    reload_button.onclick = function () { return reloadPreview(); };
    reload_button.classList.add('animated');
    var reload_anime_listener = function () {
        reload_button.classList.remove('rotate');
    };
    reload_button.addEventListener('animationend', reload_anime_listener);
    if (!config.drawer.responsive) {
        var drawer = document.getElementById('main-drawer');
        drawer.forceNarrow = true;
    }
    var menu = document.getElementById('menu');
    if (!config.menu.visible) {
        menu.style.display = 'none';
    }
    else if (config.hide_title_bar && on_darwin) {
        var spacer = document.getElementById('inset-spacer');
        spacer.style.height = '25px';
        menu.style.width = '80px';
    }
    var receiver = new Keyboard.Receiver(config.shortcuts);
    receiver.on('Lint', function () { return getMainDrawerPanel().togglePanel(); });
    receiver.on('PageUp', function () { return scrollContentBy(0, -window.innerHeight / 2); });
    receiver.on('PageDown', function () { return scrollContentBy(0, window.innerHeight / 2); });
    receiver.on('PageLeft', function () { return scrollContentBy(-window.innerHeight / 2, 0); });
    receiver.on('PageRight', function () { return scrollContentBy(window.innerHeight / 2, 0); });
    receiver.on('ChangePath', function () { return onPathButtonPushed(); });
    receiver.on('QuitApp', function () { return electron_1.remote.app.quit(); });
    receiver.on('PageTop', function () {
        var scroller = getScroller();
        if (scroller) {
            scroller.scrollTop = 0;
        }
    });
    receiver.on('PageBottom', function () {
        var scroller = getScroller();
        if (scroller) {
            scroller.scrollTop = scroller.scrollHeight;
        }
    });
    receiver.on('DevTools', function () {
        this.bw = this.bw || electron_1.remote.BrowserWindow;
        this.bw.getFocusedWindow().openDevTools({ detach: true });
    });
    receiver.on('Reload', function () { return reloadPreview(); });
    receiver.on('Print', function () { return electron_1.remote.getCurrentWindow().webContents.print(); });
    receiver.on('Search', function () { return onSearchButtonPushed(); });
    receiver.on('Outline', function () { return onTOCButtonPushed(); });
    searcher.onMount = function () {
        receiver.enabled = false;
    };
    searcher.onUnmount = function () {
        receiver.enabled = true;
    };
    toc.onMount = function () {
        receiver.enabled = false;
    };
    toc.onUnmount = function () {
        receiver.enabled = true;
    };
    electron_1.ipcRenderer.on('shiba:choose-file', function () { return onPathButtonPushed(); });
    electron_1.ipcRenderer.on('shiba:lint', function () { return getMainDrawerPanel().togglePanel(); });
    electron_1.ipcRenderer.on('shiba:outline', function () { return onTOCButtonPushed(); });
    electron_1.ipcRenderer.on('shiba:search', function () { return onSearchButtonPushed(); });
    electron_1.ipcRenderer.on('shiba:reload', function () { return reloadPreview(); });
    var user_css_path = path.join(config._config_dir_path, 'user.css');
    fs.access(user_css_path, function (err) {
        var exists = !err;
        if (!exists) {
            return;
        }
        var link = document.createElement('link');
        link.rel = 'stylesheet';
        link.type = 'text/css';
        link.href = 'file://' + user_css_path;
        document.head.appendChild(link);
    });
})();
//# sourceMappingURL=index.js.map