const log = require('electron-log');// error // warn // info // verbose // debug // silly

const getRemoteData = require('./get-remote-data');
const dataController = require('./data-controller');

module.exports = function () {
    return new Promise(function (resolve, reject) {
        try {
            const transformForNewFormat = (items) => {
                items.forEach((item) => {
                    if (item.script && !item.script.length) {
                        const newItem = item.script;

                        item.script = [newItem];
                        item.block_dur = parseInt(newItem.script_duration_base, 10) / 60;

                        item.script[0].script_content.forEach((content) => {
                            content.content_duration = [content.content_duration];
                            content.content_volume_range = [content.content_volume_range];
                            content.content_server_path = [content.content_server_path];
                            content.content_hash = [content.content_hash];
                            content.start_time = [0];
                        });
                    }
                });
            };
            const mergeResult = (data) => {
                const newBroadcasts = JSON.parse(JSON.stringify(data.broadcasts));

                if (newBroadcasts._ads) {
                    transformForNewFormat(newBroadcasts._ads);
                }

                if (newBroadcasts._info) {
                    transformForNewFormat(newBroadcasts._info);
                }

                return {
                    last_update: data.infoData.last_update,
                    ip: data.infoData.ip,
                    main_ip: data.infoData.main_ip,
                    g_volume: data.infoData.g_volume,
                    filenames: data.infoData.filenames,
                    data: newBroadcasts
                };
            };

            getRemoteData()
                .then((data) => {
                    const result = mergeResult(data);
                    log.info('getJsonData result:', result);
                    resolve(result);
                })
                .catch(async (e) => {
                    log.error('getRemoteData broken', e);
                    // log.info('return local data');

                    const data = await dataController.getInfoDataWithBroadcasts();
                    const result = mergeResult(data);
                    // log.info('getJsonData result:', result);
                    resolve(result);
                });
        } catch (err) {
            log.error(err);
            reject(new Error('getJsonData() catch error'));
        }
    });
};
