import { HttpException, HttpStatus, Inject, Injectable, NotFoundException } from '@nestjs/common';
import { CreateAttachmentDto,UpdateAttachmentDto } from './dto/attachment.dto';


import { TypeOrmQueryService } from '@nestjs-query/query-typeorm';
import { Attachment } from './attachment.entity';
import { InjectConnection, InjectRepository } from '@nestjs/typeorm';
import { Connection, Not, Repository } from 'typeorm';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';
import { TokenPayload } from 'src/types/token-payload.type';
import { ConfigService } from 'nestjs-config';
import { JwtService } from '@nestjs/jwt';
import { IPaginationOptions, paginate } from 'nestjs-typeorm-paginate';

@Injectable()
export class AttachmentService extends TypeOrmQueryService<Attachment> {
  constructor(
    @InjectRepository(Attachment)
    private readonly attachmentRepository: Repository<Attachment>,
    private readonly jwtService: JwtService,
    private readonly config: ConfigService,
    @Inject(REQUEST) private readonly request: Request,
    @InjectConnection() private readonly connection: Connection
  ) {
    super(attachmentRepository, { useSoftDelete: true });
  }


  async create(data: CreateAttachmentDto, request, files) {
    try {
      console.log("files",files);

      const attachment: Attachment = new Attachment();
      files.forEach(async file => {
      attachment.name = process.env.HOST_FILES+file.filename;
      // attachment.name = ['http://localhost:3000/'+file.filename];
      attachment.attachment_type = data.attachment_type;

      var inserted = await this.attachmentRepository.save(attachment);
    });
      // return this.getAttachmentActivityId(data.activity_id,data.tokenId);
      return "attached";
    } catch (err) {
      throw err
    }
  }


  async getAttachment(id: number) {
    try {
      return this.attachmentRepository.findOneBy({ id });
    } catch (ex) {
      throw ex;
    }
  }



  
  async getAttachments(
    options?: IPaginationOptions
  ) {
    try {
      return this.attachmentRepository.find();
    } catch (ex) {
      throw ex;
    }
  }

  

  findAll() {
    return `This action returns all service`;
  }

  findOne(id: number) {
    return `This action returns a #${id} service`;
  }


  async update(id: number, data: UpdateAttachmentDto, request) {
    try {
      console.log(data);
      const attachment: Attachment = new Attachment();
      attachment.name = data.name;
      return await this.getAttachment(id);
    } catch (ex) {
      throw ex;
    }
  }

  remove(id: number) {
    return `This action removes a #${id} service`;
  }
}
