/** @file
 * @author Edouard DUPIN
 * @copyright 2018, Edouard DUPIN, all right reserved
 * @license PROPRIETARY (see license file)
 */

import { Injectable } from '@angular/core';

import { GenericDataService } from './GenericDataService';
import { environment } from 'environments/environment';
import { RESTConfig } from 'app/back-api/rest-tools';
import { UserMediaAdvancement, UserMediaAdvancementResource } from 'app/back-api';
import { DataStore, SessionService } from '@kangaroo-and-rabbit/kar-cw';

@Injectable()
export class AdvancementService extends GenericDataService<UserMediaAdvancement> {

	getRestConfig(): RESTConfig {
		return {
			server: environment.server.karideo,
			token: this.session.getToken()
		}
	}
	private lambdaGets(): Promise<UserMediaAdvancement[]> {
		return UserMediaAdvancementResource.gets({ restConfig: this.getRestConfig() });
	}

	constructor(private session: SessionService) {
		super();
		console.log('Start ArtistService');
		const self = this;
		this.setStore(new DataStore<UserMediaAdvancement>(() => self.lambdaGets()));
	}
	get(id: number): Promise<UserMediaAdvancement> {
		return new Promise((resolve, reject) => {
			super.getFilter((data: any) => { return data.mediaId == id }).then((data: UserMediaAdvancement[]) => {
				resolve(data[0]);
				return;
			}).catch((reason: any) => {
				reject(reason);
			});
		});
	}
	updateTime(id: number, time: number, total: number, addCount: boolean) {
		const data = {
			time,
			percent: time / total,
			addCount
		};
		const self = this;
		return new Promise((resolve, reject) => {
			UserMediaAdvancementResource.patch({
				restConfig: this.getRestConfig(),
				params: {
					id
				},
				data
			}).then((value: UserMediaAdvancement) => {
				self.dataStore.updateValue(value);
				resolve(value);
			}).catch((error) => {
				reject(error);
			});
		});
	}

}

