(function (realWindow) {
    const subgameControllerKey = '_______subgame_func';
    const subGameKey = '"%{subgame_key}"';

    let subGameWindow;
    let subgameMain;
    let propertyBackup = {};
    let Loki = realWindow['Loki'] || { pushLog: () => { realWindow.cc.log() } };

    realWindow[subgameControllerKey] = realWindow[subgameControllerKey] || {};
    realWindow[subgameControllerKey][subGameKey] = {
        init: () => {
            Loki.pushLog(`SubgameController[${subGameKey}]: init`);
            const cc = realWindow.cc;
            const sg = realWindow.sg;
            const window = subGameWindow = { cc, sg };

            "%{subgame_content}"

            subgameMain = window['SubGameMain'];
            return subgameMain;
        },

        load: () => {
            Loki.pushLog(`SubgameController[${subGameKey}]: load`);
            if (!propertyBackup['collisionMatrix']) {
                Loki.pushLog(`SubgameController[${subGameKey}]: property backup, collisionMatrix = ${JSON.stringify(cc.game['collisionMatrix'])}`);

                propertyBackup['collisionMatrix'] = cc.game['collisionMatrix'];
                cc.game['collisionMatrix'] = "%{subgame_collision_matrix}";
            }

            if (!propertyBackup['groupList']) {
                Loki.pushLog(`SubgameController[${subGameKey}]: property backup, groupList = ${JSON.stringify(cc.game['groupList'])}`);

                propertyBackup['groupList'] = cc.game['groupList'];
                cc.game['groupList'] = "%{subgame_group_list}";
            }
        },

        destroy: () => {
            Loki.pushLog(`SubgameController[${subGameKey}]: destroy`);
            if (propertyBackup['collisionMatrix']) {
                Loki.pushLog(`SubgameController[${subGameKey}]: property restore, collisionMatrix = ${JSON.stringify(propertyBackup['collisionMatrix'])}`);
                cc.game['collisionMatrix'] = propertyBackup['collisionMatrix'];
                propertyBackup['collisionMatrix'] = null;
            }

            if (propertyBackup['groupList']) {
                Loki.pushLog(`SubgameController[${subGameKey}]: property restore, groupList = ${JSON.stringify(propertyBackup['groupList'])}`);
                cc.game['groupList'] = propertyBackup['groupList'];
                propertyBackup['groupList'] = null;
            }
        },

        main: () => { return subgameMain },
        window: () => { return subGameWindow }
    }
})(window);