import { Service, Inject } from 'typedi';
import { Repository } from 'typeorm';
import { InjectRepository } from 'typeorm-typedi-extensions';
import { WhereInput } from '@joystream/warthog';
import { WarthogBaseService } from '../../WarthogBaseService';

import { {{className}} } from './{{kebabName}}.model';

import { {{#variantNames}} {{.}}, {{/variantNames}} } from '../variants/variants.model'

import {
  {{className}}WhereArgs,
  {{className}}WhereInput,
} from '{{{generatedFolderRelPath}}}';

{{#fieldResolverImports}}
  {{{.}}}
{{/fieldResolverImports}}

@Service('{{className}}Service')
export class {{className}}Service extends WarthogBaseService<{{className}}> {
 {{#fieldResolvers}}
    @Inject('{{returnTypeFunc}}Service') 
    public readonly {{fieldName}}Service!: {{returnTypeFunc}}Service
  {{/fieldResolvers}}
  
  constructor(
    @InjectRepository({{className}}) protected readonly repository: Repository<{{className}}>,
  ) {
    super({{className}}, repository);
  }


  async find<W extends WhereInput>(
		where?: any,
		orderBy?: string | string[],
		limit?: number,
		offset?: number,
		fields?: string[]
	): Promise<{{className}}[]> {
    {{#has.union}}
      let records = await this.findWithRelations<W>(where, orderBy, limit, offset, fields);
      if (records.length) {
        {{#fields}}
          {{#is.union}}
            {{#fieldVariantMap}}
            records = await {{type}}.fetchData{{field}}(records, '{{camelName}}')
            {{/fieldVariantMap}}
          {{/is.union}}
        {{/fields}}
      }
      return records;
    {{/has.union}}
    
    {{^has.union}} return this.findWithRelations<W>(where, orderBy, limit, offset, fields); {{/has.union}}
  }
  

  async findWithRelations<W extends WhereInput>(
		_where?: any,
		orderBy?: string | string[],
		limit?: number,
		offset?: number,
		fields?: string[]): Promise<{{className}}[]> {
    const limitOffset = {
      limit: limit || 50,
      offset
    };

    return this.buildFindQuery(_where, orderBy, limitOffset, fields).getMany();
  }
    

}
