import {
  Controller,
  Get,
  Post,
  Body,
  Param,
  UseInterceptors,
  UploadedFile,
  Query,
  StreamableFile,
  UseGuards,
  Res
} from '@nestjs/common';
import { PointOfInterestService } from './PointOfInterest.service';
import { CreatePointAndTradDto } from './dto/create-pointAndTraduction.dto';
import { ApiBearerAuth, ApiBody, ApiConsumes, ApiParam, ApiQuery, ApiTags } from '@nestjs/swagger';
import { Roles } from 'src/auth/role.decorator';
import { ADMIN_ROLES } from 'src/shared/enum/admin-role.enum';
import { fileInterceptor } from 'src/shared/interceptors/file-save.interceptor';
import { FileValidationPipe } from 'src/shared/pipe/file-validation.pipe';
import { LANGUAGES } from 'src/shared/enum/languages.enum';
import { AuthAdminGuard } from 'src/auth/admin/authAdmin.guard';

@Controller('')
@ApiTags('Point of interest')
export class PointOfInterestController {
  constructor(private readonly pointService: PointOfInterestService) {}

  @ApiConsumes('multipart/form-data')
  @UseGuards(AuthAdminGuard)
  @Roles(ADMIN_ROLES)
  @ApiBearerAuth('jwt')
  @Post('point')
  @UseInterceptors(fileInterceptor('image', 'static/points/', ['.jpg', '.jpeg', '.png']))
  async create(@UploadedFile(new FileValidationPipe()) file, @Body() createActivityDto: CreatePointAndTradDto) {
    try {
      createActivityDto.image = file.filename;
      return await this.pointService.create(createActivityDto);
    } catch (error) {
      throw error;
    }
  }

  @ApiQuery({ name: 'lang', type: String })
  @ApiParam({ name: 'idPlace', type: Number })
  @Get('/place/:idPlace/point')
  async findAllByPlace(@Param('idPlace') idPlace: number, @Query('lang') lang: string) {
    return this.pointService.findAllByPlace(idPlace, lang as LANGUAGES);
  }

  @ApiQuery({ name: 'lang', type: String })
  @Get('point/:idPoint/audio')
  async getAudio(@Param('idPoint') idPoint: number, @Query('lang') lang: string): Promise<StreamableFile> {
    const file = await this.pointService.getAudio(idPoint, lang as LANGUAGES);
    return file;
  }

  @Get('point/:idPoint')
  @ApiQuery({ name: 'lang', type: String })
  async findOne(@Param('idPoint') idPoint: number, @Query('lang') lang: string) {
    return await this.pointService.findOne(idPoint, lang as LANGUAGES);
  }

  @ApiParam({ name: 'idPlace', type: Number })
  @ApiQuery({ name: 'pointsId', type: String })
  @Get('/place/:idPlace/point/generate')
  async generatePdf(@Param('idPlace') idPlace: number, @Query('pointsId') pointsIdString: string, @Res() res) {
    const pointsId = pointsIdString.split(',').map(Number);
    const pdfBuffer = await this.pointService.generatePdf(idPlace, pointsId);

    res.set({
      'Content-Type': 'application/pdf',
      'Content-Disposition': 'attachment; filename=tarjetas.pdf',
      'Content-Length': pdfBuffer.length,
    });

    res.send(pdfBuffer);
  }
}
