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

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

import { Media, Series, Type, TypeResource } from 'app/back-api';
import { SessionService, DataStore, TypeCheck } from '@kangaroo-and-rabbit/kar-cw';
import { RESTConfig } from 'app/back-api/rest-tools';
import { environment } from 'environments/environment';
import { GenericDataService } from './GenericDataService';
import { MediaService } from './media';
import { SeriesService } from './series';

export interface MessageLogIn {
	id: number;
	name: string;
	description: string;
}

@Injectable()
export class TypeService extends GenericDataService<Type> {
	getRestConfig(): RESTConfig {
		return {
			server: environment.server.karideo,
			token: this.session.getToken()
		}
	}
	private lambdaGets(): Promise<Type[]> {
		return TypeResource.gets({ restConfig: this.getRestConfig() });
	}

	constructor(private session: SessionService,
		private MediaService: MediaService,
		//private seriesService: SeriesService,
	) {
		super();
		console.log('Start TypeService');
		const self = this;
		this.setStore(new DataStore<Type>(() => self.lambdaGets()));
	}


	countVideo(id: number): Promise<number> {
		let self = this;
		return new Promise((resolve, reject) => {
			self.MediaService.getsWhere([
				{
					check: TypeCheck.EQUAL,
					key: 'typeId',
					value: id,
				}])
				.then((data: Media[]) => {
					resolve(data.length);
				})
				.catch((response) => {
					reject(response);
				});
		});
	}

	getSubVideo(id: number): Promise<Media[]> {
		let self = this;
		return new Promise((resolve, reject) => {
			self.MediaService.getsWhere([
				{
					check: TypeCheck.EQUAL,
					key: 'typeId',
					value: id,
				}, {
					check: TypeCheck.EQUAL,
					key: 'seriesId',
					value: undefined,
				}, {
					check: TypeCheck.EQUAL,
					key: 'universeId',
					value: undefined,
				},
			], ['name'])
				.then((data: Media[]) => {
					resolve(data);
				}).catch((response) => {
					reject(response);
				});
		});
	}

	getSubUniverse(id: number): Promise<any[]> {
		let self = this;
		return new Promise((resolve, reject) => {
			self.MediaService.getsWhere(
				[
					{
						check: TypeCheck.EQUAL,
						key: 'typeId',
						value: id,
					}, {
						check: TypeCheck.EQUAL,
						key: 'seriesId',
						value: [undefined, null],
					}, {
						check: TypeCheck.NOT_EQUAL,
						key: 'universeId',
						value: undefined,
					},
				])
				.then((data: Media[]) => {
					resolve(data);
				}).catch((response: any) => {
					reject(response);
				});
		});
	}

}

