window.ShowLinksSetup = function () {

    var customURL = app.getValue('showLinks_CustomSearchEngine', '');
    var enableCustom = app.getValue('showLinks_EnableCustomSearchEngine', false);

    window.TrackShortcuts = [
        {
            id: 1,
            grouporder: 10,
            order: 10,
            icon: 'google',
            title: 'Google',
            execute: function (type, prop, item) {
                uitools.openWebSearch('http://www.google.com/search?q=%s', type, item);
            }
        },
        {
            id: 2,
            grouporder: 10,
            order: 20,
            icon: 'wikipedia',
            title: 'Wikipedia',
            execute: function (type, prop, item) {
                uitools.openWebSearch('http://www.google.com/search?btnI=I\'m Feeling Lucky&q=%s site:wikipedia.org', type, item);
            }
        },
        {
            id: 3,
            grouporder: 10,
            order: 30,
            icon: 'youtube',
            title: 'YouTube',
            execute: function (type, prop, item) {
                uitools.openWebSearch('http://www.youtube.com/results?search_query=%s', type, item);
            }
        },
        {
            id: 4,
            grouporder: 10,
            order: 40,
            icon: 'spotify',
            title: 'Spotify',
            execute: function (type, prop, item) {
                uitools.openWebSearch('https://open.spotify.com/search/%s', type, item);
            }
        },
        {
            id: 5,
            grouporder: 10,
            order: 50,
            icon: 'discogs',
            title: 'Discogs',
            execute: function (type, prop, item) {
                uitools.openWebSearch('https://www.discogs.com/search/?q=%s&type=all', type, item);
            }
        },
        {
            id: 6,
            grouporder: 10,
            order: 60,
            icon: 'allmusic',
            title: 'AllMusic',
            execute: function (type, prop, item) {
                uitools.openWebSearch('https://www.allmusic.com/search/all/%s', type, item);
            }
        },
        {
            id: 99,
            grouporder: 20,
            order: 99,
            icon: 'library',
            title: _('Library'),
            execute: function (type, prop, item) {
                if (navigationHandlers[prop]) {
                    //#17604: Navigating to album from just album name did not navigate correctly
                    navigationHandlers[prop].navigate(item);
                }
                else console.error(`No navigationHandler for ${prop}`);
            }
        }
    ];
    
    // Add custom search engines if enabled
    for (let i = 1; i <= 3; i++) {
        let enableCustom = app.getValue(`showLinks_CustomSearchEngineEnabled_${i}`, false);
        let customURL = app.getValue(`showLinks_CustomSearchEngine_${i}`, '');
        let customTitle = app.getValue(`showLinks_CustomSearchEngineTitle_${i}`, '');
        
        window.TrackShortcuts.push({
            id: 50 + i,
            grouporder: 10,
            order: 90 + i,
            title: customTitle,
            execute: function (type, prop, item) {
                if (!enableCustom) {
                    return uitools.toastMessage.show('This custom search engine is disabled! Open the Show Links addon settings to adjust this.');
                }
                uitools.openWebSearch(customURL, type, item);
            },
            visible: enableCustom,
            icon: 'add',
        })
    }

    var handleShortcut = function (shortcut, type, prop, item) {
        // console.log('handleShortcut was called', prop);
        let shortcutExecuted = false; 
        let track;
        if (typeof item.getFastSD === 'function') // it is PlaylistEntry, get its track
            track = item.getFastSD(track);
        else
            track = item;

        for (var i = 0; i < TrackShortcuts.length; i++) {
            if (TrackShortcuts[i].id === shortcut) {
                if (TrackShortcuts[i].execute) {
                    TrackShortcuts[i].execute(type, prop, track);
                    // console.log('Executing:', TrackShortcuts[i]);
                    shortcutExecuted = true;
                }
                break;
            }
        }
        if (!shortcutExecuted) {
            TrackShortcuts[0].execute(type, prop, track);
            // console.log('Executing by default:', TrackShortcuts[0]);
        }
    };

    window.uitools.tracklistFieldDefs.title.shortcutFunc = function (item, shortcutID) {
        handleShortcut(shortcutID, 'title', 'title', item);
    }

    window.uitools.tracklistFieldDefs.artist.shortcutFunc = function (item, shortcutID) {
        handleShortcut(shortcutID, 'artist', 'artist', item);
    }

    window.uitools.tracklistFieldDefs.album.shortcutFunc = function (item, shortcutID) {
        handleShortcut(shortcutID, 'album', 'album', item);
    }

    window.uitools.tracklistFieldDefs.albumArtist.shortcutFunc = function (item, shortcutID) {
        handleShortcut(shortcutID, 'albumArtist', 'albumartist', item);
    }

    window.uitools.tracklistFieldDefs.series.shortcutFunc = function (item, shortcutID) {
        handleShortcut(shortcutID, 'album', 'album', item);
    }
    
    TrackListView.prototype.override({
        initialize: function ($super, elem, params) {
            $super(elem, params);
            this._showShortcuts = true;
    
            var loadSettings = () => {
                var sett = settings.get('Options');
                this._activeShortcut = sett.Options.ActiveTrackShortcutType;
            };
            loadSettings();

            this.localListen(settings.observer, 'change', () => {
                loadSettings();
            });
        },
    });

    TrackListView.prototype.getShortcutContextMenu = (parent, column) => {
        var presetColumns = [];
        TrackShortcuts.sort(function (i1, i2) {
            return i1.order - i2.order;
        });
        forEach(TrackShortcuts, function (shortcut, idx) {
            presetColumns.push({
                action: {
                    title: shortcut.title,
                    icon: shortcut.icon,
                    execute: function () {
                        if (parent.parentElement.itemIndex >= 0) {
                            var LV = parent.parentElement.parentListView;
                            var item = undefined, songData = undefined;
                            item = LV.focusedItem;
                            // if getFastSD is a function, that means this is a playlist entry, not a song data object
                            if (typeof item.getFastSD === 'function') {
                                songData = item.getFastSD(songData);
                            }
                            else {
                                songData = item;
                            }
                            column.shortcutFunc(songData, shortcut.id);
                        }
                    },
                    visible: shortcut.visible,
                },
                grouporder: shortcut.grouporder,
            });
        });
        return new Menu(presetColumns, {
            parent: parent
        });
    }

}

if (window.isMainWindow)
    window.ShowLinksSetup();
