import DataRefreshMixin from './data-refresh-mixin.js'

function debounce(func, wait, immediate) {
	var timeout;
	return function() {
		var context = this, args = arguments;
		var later = function() {
			timeout = null;
			if (!immediate) func.apply(context, args);
		};
		var callNow = immediate && !timeout;
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);
		if (callNow) func.apply(context, args);
	};
};

export default {
    extends: HologramWidget,
    mixins: [ DataRefreshMixin('frequency', 'pauseUpdates', 'photoUrl') ],
    data() {
        return {
            photoUrl: ''
        }
    },
    mounted() {
        // Load the widget theme colors, and assign them to css variables
        this.fetchColorTheme('theme', colors => {
            this.addCssVariables(colors)
        })

        this.debounceUpdateAPIKey = debounce(function() {
            this.forceRefreshData()
        }, 250);
    },
    methods: {
        getDataToRefresh(callback) {
            var apiKey = this.settings.apiKey.trim()

            if (apiKey == "") {
                callback(this.getApiKeyImage())
                return
            }

            // Construct the date
            let daysBack = 2
            var t = new Date()
            t.setDate(t.getDate() - daysBack)
            let y = t.getFullYear()
            let m = t.getMonth() + 1
            let d = t.getDate()

            // Create the fetch url
            var url = 'https://api.nasa.gov/planetary/apod?api_key=' + apiKey + '&date=' + y + '-' + m + '-' + d
            
            fetch(url)
            .then(response => response.json())
            .then(data => {
                if (!data) {
                    callback(this.getRandomLocalImage())
                    return
                }

                // Is there an error?
                if (data.error) {
                    let code = data.error.code

                    if (code == 'API_KEY_INVALID') {
                        callback(this.asset('images/api-invalid.jpg'))
                        return
                    }

                    callback(this.getRandomLocalImage())
                    return
                }

                // Get the url from the API request
                let url = data.url || ''

                // Only allow images from nasa.gov
                if (!url.includes('apod.nasa.gov')) {
                    callback(this.getRandomLocalImage())
                    return
                }

                callback(url)
            })
            .catch(e => {
                callback(this.getRandomLocalImage())
            })
        },

        getApiKeyImage() {
            return this.asset('images/api.jpg')
        },

        getRandomLocalImage() {
            // If the server response is bad or if the file is not
            // from NASA (they sometimes push stuff from youtube or vimeo) we get a random local image.
            var rand = Math.floor(Math.random() * 20) + 1
            rand = rand.toString()
            if (rand.length == 1) {
                rand = '0' + rand
            }
            return this.asset('images/' + rand + '.jpg')
        },
    },
    watch: {
        'settings.apiKey': function() {
            this.debounceUpdateAPIKey()
        },
    },
    template: /*html*/ `
        <div class="widget-container" :style="{'--shadow': this.settings.shadow.boxShadow, '--borderWidth': settings.borderWidth + 'px', borderRadius: (settings.borderRadius / 100) + 'em'}">
            <div class="photo" :style="{'background-image': 'url(' + photoUrl + ')'}"></div>
        </div>
    `
}