"use strict";
const project = require('./package.json');
const serviceName = project.name;
const packageLoader = require('@steedos/service-package-loader');

const rests = require('./src/rests');
const InstanceRecordQueue = require('./src/instance_record_queue')
const WebhookQueue = require('./src/webhook_queue')

/**
 * @typedef {import('moleculer').Context} Context Moleculer's Context
 */
module.exports = {
	name: serviceName,
	namespace: "steedos",
	mixins: [packageLoader],
	settings: {
		
	},
	metadata: {
		$package: {
			name: serviceName,
			path: __dirname,
			isPackage: false
		}
	},
	/**
	 * Dependencies
	 */
	dependencies: ['@steedos/service-core-objects'],
	/**
	 * Actions
	 */
	actions: {
		...rests,

		create_instance: {
			params:
			{
				instance: { type: 'object', optional: false },
				user: { type: 'object', optional: false },
			},
			async handler(ctx) {
				try {
					const { instance, user } = ctx.params;
					let new_ins_id = UUFlowManager.create_instance(instance, user);
					return new_ins_id
				} catch (error) {
					console.error(error);
					return false;
				}
			}
		},
		send_badge_to_user: {
			params: {
				send_from: { type: 'string', optional: false },
				user_id: { type: 'string', optional: false }
			},
			async handler(ctx) {
				try {
					const { send_from, user_id } = ctx.params;
					pushManager.send_message_to_specifyUser(send_from, user_id);
					return true;
				} catch (error) {
					console.error(error);
					return false
				}
			}
		}
	},

	/**
	 * Events
	 */
	events: {
		"@steedos_keyvalues.*": {
			async handler(ctx) {
				const { doc } = ctx.params;
				if(doc.space && doc.key === 'badge'){
					await ctx.broker.emit('$socket.emit', {
						eventName: 's:workflow:badge:change',
						eventParams: doc.value,
						room: `${doc.space}-workflow:badge:change-${doc.user}`
					})
				}

			}
		},
		'$socket.subscribe.workflow:badge:change': {
			async handler(ctx) {
				const {space, userId} = ctx.params;
				if(space && userId){
					setTimeout(async ()=>{
						const records = await this.getObject("steedos_keyvalues").directFind({
							filters: [['space', '=', space], ['user', '=', userId], ['key', '=', 'badge']]
						})
						for (const doc of records) {
							await ctx.broker.emit('$socket.emit', {
								eventName: 's:workflow:badge:change',
								eventParams: doc.value,
								room: `${doc.space}-workflow:badge:change-${doc.user}`
							})
						}
					}, 1000 * 3)
				}
			}
		}
	},

	/**
	 * Methods
	 */
	methods: {

	},

	/**
	 * Service created lifecycle event handler
	 */
	async created() {

	},

	/**
	 * Service started lifecycle event handler
	 */
	async started(ctx) {
		if((process.env.STEEDOS_CRON_ENABLED === true || process.env.STEEDOS_CRON_ENABLED === 'true')){

			if (process.env.STEEDOS_CRON_INSTANCERECORDQUEUE_INTERVAL)  {
				InstanceRecordQueue.Configure({
					sendInterval: process.env.STEEDOS_CRON_INSTANCERECORDQUEUE_INTERVAL,
					sendBatchSize: 10,
					keepDocs: true
				})
			}
			
			// webhooks 流程触发器 队列
			if (process.env.STEEDOS_CRON_WEBHOOKQUEUE_INTERVAL)  {
				await WebhookQueue.Configure({
					sendInterval: process.env.STEEDOS_CRON_WEBHOOKQUEUE_INTERVAL,
					sendBatchSize: 10,
					keepDocs: false
				})
			}

		}
	},

	/**
	 * Service stopped lifecycle event handler
	 */
	async stopped() {

	}
};
