'use strict';

import {serializeError} from "serialize-error";

let system = function () {
	return {
		integration: (data = {}) => {
			return this.__privates.auth.__client
				.then(client => client.apis.system.integration({type: this.__instanceType}, {
					requestBody: {...data}, requestInterceptor: (req) => {
						if (!req.headers) {
							req.headers = {};
						}
						req.headers['Authorization'] = 'Bearer ' + localStorage.getItem('rwt_idToken');
						return req;
					}
				}));
		},
		
		getAnalytics: (data = {}) => {
			return this.__privates.auth.__client
				.then(client => client.apis.system.getAnalytics({instanceType: this.__instanceType, ...data}))
		},
		
		getTranslation: ({namespace = 'wt'} = {}) => {
			return this.__privates.auth.__client
				.then(client => client.apis.system.getTranslation({namespace}))
		},

		getConfig: ({instanceType = this.__instanceType, domain = location.hostname} = {}) => {
			return this.__privates.auth.__client
				.then(client => client.apis.system.getConfig({instanceType, domain}));
		},

		updateConfig: (data = {}) => {
			return this.__privates.auth.__client
				.then(client => client.apis.system.updateConfig({id: data.instanceType || this.__instanceType},{requestBody:{...data}}));
		},

		getIntegrationPublic: (type, data = {}) => {
			return this.__privates.auth.__client
				.then(client => client.apis.system.integrationPublic({type}, {requestBody:{...data}}))
		},
		admin: (data = {}) => {
			return this.__privates.auth.__client
				.then(client => client.apis.wt.admin({},{requestBody:{instanceType : this.__instanceType, ...data}}));
		},
		analytics: ({action, startKey = null, limit = 20} = {}) => {

			let apiParams = {
				action,
				limit,
				...(startKey && {startKey})
			};
			return this.__privates.auth.__client
				.then(client => client.apis.wt.analytics({},{requestBody:{instanceType : this.__instanceType, ...apiParams}}));

		},
		track: ({eventType = 'ERROR', message} = {}) => {
			return this.__privates.auth.__client
				.then(client => client.apis.wt.track({},{
					requestBody:{
						"eventType": eventType,
						"appType": "web",
						"deviceType": `desktop${navigator.maxTouchPoints ? '/touch' : ''}`,
						"os": navigator.platform,
						"browser": navigator.userAgent,
						"domain": location.host,
						"url": location.href,
						"message": serializeError(message)
					}
				}));
		},
		getSchemas: () => {
			return this.__privates.auth.__client.then(client => {
				return client.spec?.components?.schemas
			})
		},

		getClient: () => {
			return this.__privates.auth.__client.then(client => {
				return client
			});
		}
	}
}

export default system;