import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import {
  SearchParams,
  SearchResult,
  SearchResultInfo,
} from '@csr/common/entities'
import { LengthClass } from '../entities/length.class'

import { LengthClassDto } from '../dtos/length.class.dto'

@Injectable()
export class LengthClassService {
  constructor(
    @InjectRepository(LengthClass)
    private readonly lengthClassRepository: Repository<LengthClass>,
  ) {}

  async search(params: SearchParams): Promise<SearchResult<LengthClass>> {
    const where = {}
    const [data, count] = await this.lengthClassRepository.findAndCount({
      where,
      take: params.limit,
      skip: params.getSkip(),
    })

    const info = new SearchResultInfo({
      page: params.page,
      pages: Math.ceil(count / params.limit),
      pageSize: params.limit,
      count,
    })
    return new SearchResult<LengthClass>(data, info)
  }

  async get(id: number): Promise<LengthClass> {
    return this.lengthClassRepository.findOne({
      where: {
        id: id,
      },
    })
  }

  async create(lengthClassDto: LengthClassDto): Promise<LengthClass> {
    const lengthClass = new LengthClass()
    this.fill(lengthClass, lengthClassDto)

    return this.lengthClassRepository.save(lengthClass)
  }

  async update(
    id: number,
    lengthClassDto: LengthClassDto,
  ): Promise<LengthClass> {
    const lengthClass = await this.lengthClassRepository.findOneBy({ id: id })
    this.fill(lengthClass, lengthClassDto)

    return this.lengthClassRepository.save(lengthClass)
  }

  async save(lengthClass: LengthClass): Promise<LengthClass> {
    return this.lengthClassRepository.save(lengthClass)
  }

  async delete(id: number): Promise<void> {
    await this.lengthClassRepository.delete(id)
  }

  async fill(
    lengthClass: LengthClass,
    lengthClassDto: LengthClassDto,
  ): Promise<void> {
    lengthClass.name = lengthClassDto.name
    lengthClass.code = lengthClassDto.code
    lengthClass.value = lengthClassDto.value
    lengthClass.isDefault = lengthClassDto.isDefault
    lengthClass.isActive = lengthClassDto.isActive
  }
}
