
const electron  = require( 'electron' ),
      path      = require( 'path' ),
      ipc       = electron.ipcRenderer,
      remote    = electron.remote,
      root      = remote.process.env[ 'NODE_ENV' ] ? './src/main/inject/' : path.join( __dirname, '../../inject/' );

window.$        = window.jQuery = require( root + 'simpread/vender/jquery-3.3.1.min.js' );
window.puplugin = require( root + 'simpread/vender/puread/puplugin.min.js' );
window.PureRead = require( root + 'simpread/vender/puread/puread.min.js' );
window.hljs     = require( root + 'simpread/vender/highlight.min.js' );
window.sites    = require( root + 'simpread/assets/static/website_list.json' );

const pr        = new PureRead()

/**
 * Render
 */
function ready() {
    pr.Addsites( sites );
    pr.cleanup = true;
    pr.pure    = true;
    pr.AddPlugin( puplugin.Plugin() );
    pr.Getsites();
    pr.ReadMode();

    if ( pr && pr.html && pr.html.include == '<sr-rd-content-error></sr-rd-content-error>' ) {
        setTimeout( () => {
            pr.Getsites();
            pr.ReadMode();
            readModeRender();
        }, 2000 );
    } else if ( pr && pr.html && pr.html.include != '' ) {
        readModeRender()
    }
}

/**
 * Read mode
 */
function readModeRender() {
    console.log( "=== Current pureread is ", pr );
    const $root = $( 'html' ),
        tmpl  = `<div class="simpread-read-root">
                        <sr-read style="margin: 20px 10%;">
                            <sr-rd-title></sr-rd-title>
                            <sr-rd-desc></sr-rd-desc>
                            <sr-rd-content class="embed"></sr-rd-content>
                            <sr-page></sr-page>
                        </sr-read>
                    </div>`;
    $root.append( tmpl );

    $( 'sr-rd-title'   ).html( pr.html.title );
    $( 'sr-rd-content' ).html( pr.html.include );

    $('sr-rd-content').find( pr.Exclude( $('sr-rd-content') )).remove();
    pr.Beautify( $( 'sr-rd-content' ));
    pr.Format( 'simpread-read-root' );

    $( "sr-rd-content" ).find( "img.sr-rd-content-img-load" ).removeClass();

    hljsRender();

    ipc.send( 'dom', $( "sr-rd-content" )[0].outerHTML );
}

/**
 * Highlight
 */
function hljsRender() {
    document.querySelectorAll( 'pre' ).forEach( block => {
        hljs && hljs.highlightBlock( block );
    });
}

ready();