<script>
import SpotButton from '@components/spotButton';
import SpotIcon from '@components/spotIcon';

export default {
	components: {
		SpotButton,
		SpotIcon
	},
	data() {
		return {
			feedbacks: [],
			loading: false
		};
	},
	computed: {
		buttonClasses() {
			return [
				'manage',
				this.action,
				this.loading?'loading':''
			].filter(n => n).join(' ');
		},
		subscribed() {
			return this.user.id_user > 0;
		},
		action() {
			return this.subscribed?'unsubscribe':'subscribe';
		}
	},
	inject: ['api', 'lang', 'user'],
	methods: {
		manage() {
			if(this.loading) return;

			var regexEmail = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
			if(!regexEmail.test(this.user.email)) this.feedbacks.push({type:'error', 'msg':this.lang.get('newsletter.invalid_email')});
			else {
				const sAction = this.action;
				this.loading = true;

				this.api.request(sAction, {'email': this.user.email, 'name': this.user.name}, 'POST')
					.then((asResponse) => {
						this.feedbacks.push({type: asResponse.result, msg: asResponse.desc});
						this.user.setInfo(asResponse.data);
					})
					.catch((sDesc) => {this.feedbacks.push({type:'error', msg:sDesc?.message || sDesc});})
					.finally(() => {this.loading = false;});
			}
		}
	}
}
</script>

<template>
	<div class="newsletter-form">
		<input type="email" name="email" id="email" :placeholder="lang.get('newsletter.email_placeholder')" v-model="user.email" :disabled="loading || subscribed" />
		<SpotButton :classes="buttonClasses" :title="lang.get('newsletter.'+action)" :icon="action" @click="manage" />
	</div>
	<div class="feedback">
		<p v-for="feedback in feedbacks" :key="feedback.type + '-' + feedback.msg" :class="feedback.type">
			<SpotIcon :icon="feedback.type" :text="feedback.msg" />
		</p>
	</div>
	{{ lang.get('newsletter.'+(subscribed?'subscribed':'unsubscribed')+'_desc') }}
</template>
