import { Injectable } from '@nestjs/common';
import { ModelService } from '../model/model.service';
import * as dto from './dto/index'

@Injectable()
export class DocumentService {
  constructor(
    private readonly ModelService: ModelService
  ) {

  }

  async get_document(body: dto.pl) {
    try {
      let { pagination, limit } = body
      let options = await this.set_options(pagination, limit)
      let data = await this.ModelService.documentsModel.find({}, {}, options)
      let count = await this.ModelService.documentsModel.countDocuments()
      return { count: count, data: data }
    } catch (error) {
      throw error
    }
  }


  async set_options(pagination: number, limit: number) {
    try {
      // console.log("-=-=-pagination------",pagination,limit)
      let options: any = {
        lean: true,
        sort: { _id: -1 }
      }

      if (pagination == undefined && limit == undefined) {
        options = {
          lean: true,
          sort: { _id: -1 },
          limit: 10,
          pagination: 0,
          skip: 0
        }
      }
      else if (pagination == undefined && typeof limit != undefined) {
        options = {
          lean: true,
          sort: { _id: -1 },
          limit: Number(limit),
          skip: 0,
        }
      }
      else if (typeof pagination != undefined && limit == undefined) {
        options = {
          lean: true,
          sort: { _id: -1 },
          skip: Number(pagination) * Number(process.env.DEFAULT_LIMIT),
          limit: Number(process.env.DEFAULT_LIMIT)
        }
      }
      else if (typeof pagination != undefined && typeof limit != undefined) {
        options = {
          lean: true,
          sort: { _id: -1 },
          limit: Number(limit),
          skip: Number(pagination) * Number(limit)
        }
      }
      return options
    }
    catch (err) {
      throw err;
    }
  }
}
