/*
Check this out later: https://zhirzh.github.io/2017/01/30/browser-history-functioning-&-loopback-gotcha/
*/

export default class FlexRouter {

    static gotoSingleSearch = queryId => {
        let url = FlexRouter.__getBaseUrl() + '/tool/single-search';
        if (queryId) {
            url += '?queryId=' + queryId;
        }
        document.location.href = url;
    };

    static gotoQueryComparisonTool = () => {
        document.location.href = FlexRouter.__getBaseUrl() + '/tool/query-comparison'
    };

    static gotoResourceViewerOld = (itemDetailsRecipePath, searchResult, searchTerm, hideNavigationBtns=false) => {
        if(!searchResult) return false;
        let url = FlexRouter.__getBaseUrl() + '/' + itemDetailsRecipePath + '?id=' + searchResult.resourceId;
        url += '&cid=' + (searchResult.collectionId || searchResult.index);
        if(searchTerm) {
            url += '&st=' + searchTerm;
        }
        // flag to let the component know if it should hide navigation btns.
        if(hideNavigationBtns) {
            url += '&bodyClass=noHeader'
        }
        //check the collection config to see how the mediaFragment was added to the result object
        if(searchResult.mediaFragment) {
            /*
                FIXME the URL should be a "safe" URL, so for B&G only the safe play-out link should be shown.
                Also the resource viewer must be able to identify the right media object using this safe URL
            */

            //TODO test this change to assetId thoroughly!
            //if(searchResult.mediaFragment.hasOwnProperty('url')) { url += '&fragmentUrl=' + searchResult.mediaFragment.url; }
            if(searchResult.mediaFragment.hasOwnProperty('assetId')) { url += '&assetId=' + searchResult.mediaFragment.assetId; }

            if(searchResult.mediaFragment.hasOwnProperty('start')) { url += '&s=' + searchResult.mediaFragment.start; }
            if(searchResult.mediaFragment.hasOwnProperty('end')) { url += '&e=' + searchResult.mediaFragment.end; }
            if(searchResult.mediaFragment.hasOwnProperty('x')) { url += '&x=' + searchResult.mediaFragment.x; }
            if(searchResult.mediaFragment.hasOwnProperty('y')) { url += '&y=' + searchResult.mediaFragment.y; }
            if(searchResult.mediaFragment.hasOwnProperty('w')) { url += '&w=' + searchResult.mediaFragment.w; }
            if(searchResult.mediaFragment.hasOwnProperty('h')) { url += '&h=' + searchResult.mediaFragment.h; }
            if(searchResult.mediaFragment.hasOwnProperty('layer')) { url += '&l=' + searchResult.mediaFragment.layer; }
        }
        document.location.href = url;
    };

    //this is typically called from a search recipe after clicking a search result
    //FIXME expects a FORMATTED searchResult
    static gotoResourceViewer = (
        recipePath,
        searchResult,
        searchTerm,
        hidePageHeader = false,
        singleResource = false
    ) => {
        document.location.href = FlexRouter.getResourceViewerUrl(
            recipePath,
            searchResult,
            searchTerm,
            hidePageHeader,
            singleResource
        );
    };

    //this is typically called from a search recipe after clicking a search result
    //FIXME expects a FORMATTED searchResult
    static popupResourceViewer = (
        recipePath,
        searchResult,
        searchTerm,
        popUpName,
        singleResource,
        onCloseCallback
    ) => {
        // create the popup covering most of the current window, centered
        const popup = window.open(
            FlexRouter.getResourceViewerUrl(
                recipePath,
                searchResult,
                searchTerm,
                true,
                singleResource
            ),
            popUpName,
            'width=' +
                Math.round(window.innerWidth * 0.9) +
                ',height=' +
                Math.round(window.innerHeight * 0.9) +
                ',top=' +
                Math.round(window.screenTop + window.innerHeight * 0.05) +
                ',left=' +
                Math.round(window.screenLeft + window.innerWidth * 0.05)
        );

        // Handle close
        if (onCloseCallback) {
            // this is a fairly robust way to check if the popup has been closed
            // after closing, call the onCloseCallback function
            const pollTimer = window.setInterval(() => {
                if (popup.closed !== false) {
                    // !== is required for compatibility with Opera
                    window.clearInterval(pollTimer);
                    onCloseCallback();
                }
            }, 200);
        }
    };

    static getResourceViewerUrl = (
        recipePath,
        searchResult,
        searchTerm,
        hidePageHeader = false,
        singleResource = false
    ) => {
        if (!searchResult) return false;
        let url =
            FlexRouter.__getBaseUrl() +
            recipePath +
            '?id=' +
            searchResult.resourceId;
        url += '&cid=' + (searchResult.collectionId || searchResult.index);
        if (searchTerm) {
            url += '&st=' + searchTerm;
        }
        // flag to let the component know if it should hide the page header
        // used for popups
        if (hidePageHeader) {
            url += '&bodyClass=noHeader';
        }

        if (singleResource) {
            url += '&singleResource=1';
        }
        //check the collection config to see how the mediaFragment was added to the result object
        if (searchResult.mediaFragment) {
            /*
				FIXME the URL should be a "safe" URL, so for B&G only the safe play-out link should be shown.
				Also the resource viewer must be able to identify the right media object using this safe URL
			*/

            //TODO test this change to assetId thoroughly!
            //if(searchResult.mediaFragment.hasOwnProperty('url')) { url += '&fragmentUrl=' + searchResult.mediaFragment.url; }
            if (searchResult.mediaFragment.hasOwnProperty('assetId')) {
                url += '&assetId=' + searchResult.mediaFragment.assetId;
            }

            if (searchResult.mediaFragment.hasOwnProperty('start')) {
                url += '&s=' + searchResult.mediaFragment.start;
            }
            if (searchResult.mediaFragment.hasOwnProperty('end')) {
                url += '&e=' + searchResult.mediaFragment.end;
            }
            if (searchResult.mediaFragment.hasOwnProperty('x')) {
                url += '&x=' + searchResult.mediaFragment.x;
            }
            if (searchResult.mediaFragment.hasOwnProperty('y')) {
                url += '&y=' + searchResult.mediaFragment.y;
            }
            if (searchResult.mediaFragment.hasOwnProperty('w')) {
                url += '&w=' + searchResult.mediaFragment.w;
            }
            if (searchResult.mediaFragment.hasOwnProperty('h')) {
                url += '&h=' + searchResult.mediaFragment.h;
            }
            if (searchResult.mediaFragment.hasOwnProperty('layer')) {
                url += '&l=' + searchResult.mediaFragment.layer;
            }
        }
        return url;
    };

    //this is typically called from a collection browsing recipe after selecting a collection for closer study
    static gotoSearch = (searchRecipePath, collectionIds) => {
        const url =
            FlexRouter.__getBaseUrl() +
            '/' +
            searchRecipePath +
            '?cids=' +
            collectionIds.join(',');
        document.location.href = url;
    };

    static __getBaseUrl = () => {
        const temp = window.location.href;
        const arr = temp.split('/');
        return arr[0] + '//' + arr[2];
    };

    static __toUrlParamList = (params) => {
        let paramList = null;
        if (
            params &&
            typeof params === 'object' &&
            Object.keys(params).length > 0
        ) {
            paramList = [];
            for (const p in params) {
                paramList.push(p + '=' + params[p]);
            }
        }
        return paramList;
    };

    //TODO extend this function so it is optional to put the params in the URL
    static setBrowserHistory = (params, stateTitle) => {
        let url = document.location.pathname;
        const paramList = FlexRouter.__toUrlParamList(params);
        if (paramList) {
            url += '?' + paramList.join('&');
        }
        window.history.pushState(params, stateTitle, url);
    };

}
