<template>
	<div class="simplestats-addons-col">
		<div class="simplestats-addon-item">
			<div class="simplestats-addon-item-top">
				<div class="simplestats-addon-item-icon">
					<img :src="addon.icon" alt="">
				</div>
				<div class="simplestats-addon-item-content">
					<h4 v-text="addon.title"></h4>
					<p v-text="addon.excerpt"></p>
				</div>
			</div>
			<div class="simplestats-addon-item-bottom">
				<div class="simplestats-addon-item-bottom-status">
					{{ text_status }}: <strong :class="{'simplestats-addon-item-bottom-status-active': addon.active}">{{ getStatusText( addon ) }}</strong>
				</div>
				<button
					v-if="!addon.active"
					class="simplestats-addon-item-bottom-button"
					@click="onButtonClick(addon)"
					:disabled="loading"
				>{{ getButtonText( addon ) }}</button>
			</div>
		</div>
	</div>
</template>

<script setup>
	import { ref } from 'vue';
	import api from "@/addon-api.js";
	import { useStore } from '@/dashboard/store.js';

	const loading = ref(false);
	const store = useStore();

	const { addon } = defineProps({
		addon: {
			type: Object,
			required: true
		},
	})

	const text_status = wp.i18n.__('Status', 'simplestats-friendly-website-analytics');

	function getStatusText( addon ) {
		if ( ! addon.installed ) {
			return wp.i18n.__('Not Installed', 'simplestats-friendly-website-analytics');
		}

		if ( addon.active ) {
			return wp.i18n.__('Activated', 'simplestats-friendly-website-analytics');
		}

		return wp.i18n.__('Not Activated', 'simplestats-friendly-website-analytics');
	}

	function getButtonText( addon ) {
		if ( loading.value ) {
			return wp.i18n.__('Loading', 'simplestats-friendly-website-analytics') + '...';
		}

		if ( ! addon.installed ) {
			return wp.i18n.__('Install Plugin', 'simplestats-friendly-website-analytics');
		}

		return wp.i18n.__('Activated Plugin', 'simplestats-friendly-website-analytics');
	}

	function onButtonClick( addon ) {
		loading.value = true;

		if ( ! addon.installed ) {
			// First install then activate.
			api.installPlugin( addon.slug ).then( () => {
				return api.activatePlugin( addon.basename ).then( afterActivated );
			} );
			return;
		}

		// Plugin already installed.
		api.activatePlugin( addon.basename ).then( afterActivated );
	}

	function afterActivated() {
		store.updateAddonsList().then( () => {
			loading.value = false;
		} );
	}
</script>
