import { writable } from 'svelte/store';
import { OpenAPI, AuthService } from '@odit/lfk-client-js';
import localForage from 'localforage';

export let users = writable([]);
export let tracks = writable([]);
const store = () => {
	const state = {
		auth: undefined,
		access_token: undefined,
		jwtinfo: undefined,
		isLoggedIn: false,
		refreshInterval: undefined
	};

	const { subscribe, set, update } = writable(state);

	const methods = {
		init() {
			update((state) => {
				state.isLoggedIn = false;
				return state;
			});
		},
		refreshAuth() {
			AuthService.authControllerRefresh({ token: state.auth.refresh_token }).then((auth) => {
				OpenAPI.TOKEN = auth.access_token;
				const jwtinfo = JSON.parse(atob(auth.access_token.split('.')[1]));
				state.jwtinfo = jwtinfo;
				localForage.setItem('logindata', auth);
			}).catch(()=>{this.logout();});
		},
		login(auth, jwtinfo) {
			update((state) => {
				state.auth = auth;
				state.access_token = auth.access_token;
				state.jwtinfo = jwtinfo;
				state.isLoggedIn = true;
				//
				state.refreshInterval = setInterval(() => {
					this.refreshAuth();
					// 2min
				}, 2 * 60000);
				//
				return state;
			});
		},
		logout() {
			update((state) => {
				state.isLoggedIn = false;
				//
				clearInterval(state.refreshInterval);
				state.refreshInterval = undefined;
				//
				return state;
			});
		}
	};

	return {
		subscribe,
		set,
		update,
		state,
		...methods
	};
};
export default store();
