'use strict';

/*eslint-disable*/
var mlink = require('../midware');
var Router = mlink.Router;
var DeviceManager = require('../managers/device_manager');
// const { bundleWrapper, apiWrapper, transformUrlToLocalUrl } = require('../../util/wrapper');
var MemoryFile = require('../../lib/memory_file');
var debuggerRouter = Router.get('debugger');
var crypto = require('../../util/crypto');
var URL = require('url');
// const path = require('path');
var LOGLEVEL = {
    debug: 0,
    log: 1,
    info: 2,
    error: 3,
    warning: 4,
    warn: 4
};
debuggerRouter.registerHandler(function (message) {
    var payload = message.payload;
    if (payload.method === 'AtomDebug.initJSRuntime') {
        payload.params.url = new MemoryFile('Framework.js', payload.params.source).getUrl();
    } else if (payload.method === 'AtomDebug.importScript') {
        var filename = '';
        if (payload.params.sourceUrl) {
            var urlObj = URL.parse(payload.params.sourceUrl);
            if (urlObj.host) {
                filename = urlObj.host;
                if (urlObj.port) {
                    filename = filename + ':' + urlObj.port;
                }
            }
            if (urlObj.path) {
                filename = filename + urlObj.path;
            } else {
                filename = 'imported_' + crypto.md5(payload.params.source) + '.js';
            }
        } else {
            filename = 'imported_' + crypto.md5(payload.params.source) + '.js';
        }
        payload.params.sourceUrl = new MemoryFile(filename, payload.params.source).getUrl();
    }
    message.to('runtime.worker');
}).at('proxy.native').when('payload.method&&payload.method.split(".")[0]==="AtomDebug"');

debuggerRouter.registerHandler(function (message) {
    var payload = message.payload;
    var device = DeviceManager.getDevice(message.channelId);
    if (payload.method === 'Page.screencastFrame') {
        payload.params.sessionId = 1;
    } else if (payload.method === 'Console.messageAdded') {
        if (LOGLEVEL[payload.params.message.level] >= LOGLEVEL[device && device.logLevel ? device.logLevel : 'debug']) {
            message.payload = {
                'method': 'Runtime.consoleAPICalled',
                'params': {
                    'type': payload.params.message.level,
                    'args': [{
                        type: 'string',
                        value: payload.params.message.text
                    }] || [],
                    'executionContextId': 1
                }
            };
        } else {
            message.discard();
        }
    } else if (payload.method === 'DOM.childNodeRemoved') {
        // 此处是为了 扫bundle二维码通知页面关掉bundle二维码界面这个功能
        // 当没有打开JS Debug时 weex加载bundle devtool是不知道的 只能模糊的通过childNodeRemoved判断
        // 这个标记用来限制短时间内发出很多次通知
        var now = new Date().getTime();
        if (!device || now - (device.lastRenderedNotifyTime || 0) > 1500) {
            // 对device不存在的异常做保护
            if (device) {
                device.lastRenderedNotifyTime = now;
            }
            if (device && device.platform !== 'iOS') {
                debuggerRouter.pushMessageByChannelId('page.debugger', message.channelId, {
                    method: 'AtomDebug.bundleRendered'
                });
            }
        }
    } else if (payload.result && payload.result.method === 'AtomDebug.syncReturn') {
        message.payload = {
            error: payload.error,
            ret: payload.result.params && payload.result.params.ret
        };
        message.to('sync');
        return;
    } else if (payload.result && payload.id === undefined) {
        message.discard();
    }
    // remove useless but large message
    if (payload.method && payload.method === 'Page.screencastFrameAck') {
        message.discard();
    } else {
        message.to('proxy.inspector');
    }
    // message.to('proxy.inspector');
}).at('proxy.native').when('!payload.method||payload.method.split(".")[0]!=="AtomDebug"');
/*eslint-disable*/