import {
	Body, Controller, Delete, Get, NotFoundException, Param, Patch, Post, Query, Redirect, Req, Res, UploadedFile, UseGuards, UseInterceptors
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { Response } from 'express';
import { AuthenticateGuard, TwoFactorGuard } from 'src/auth/42/guards/42guards';
import { PaginationQueryDto } from 'src/common/dto/pagination-query.dto';
import { ValidationPipe } from 'src/common/validation/validation.pipe';
import { UpdateUsersDto } from './dto/update-users.dto';
import { UsersService } from './users.service';
import { User } from './entities/user.entity';
import { of } from 'rxjs';
import { storageForAvatar } from 'src/common/constants/constants';
import { use } from 'passport';


@Controller('user')
export class UsersController {
	constructor(private readonly usersService: UsersService) {}
	// par exemple dans postamn ou insomnia http://localhost:3000/users?limit=10&offset=20

	@UseGuards(AuthenticateGuard)
	@UseGuards(TwoFactorGuard)
	@Get('all')
	findAll(@Query() paginationquery : PaginationQueryDto) {
		//const { limit, offset } = query;
		return this.usersService.findAll(paginationquery);
	}

	////////////////////////////////////////////////////////
	///////////////////////// RUD //////////////////////////
	////////////////////////////////////////////////////////

	/**
	 * On ne fait de création via une route
	 * car un utilisateur est crée à la première connexion  avec l'Oauth de 42.
	 */

	// @UseGuards(AuthenticateGuard)
	// @UseGuards(TwoFactorGuard)
	// @Get()
	// findOne(@Req() req) {
	// 	console.log("Backend Getting current user");
	// 	return this.usersService.findOne(req.user.id);
	// }

	@UseGuards(AuthenticateGuard)
	@UseGuards(TwoFactorGuard)
	@Get()
	findOne(@Query('username') username: string, @Req() req) {
		if (username === undefined) {
			console.log("Backend Getting current user");
			return this.usersService.findOne(req.user.id);
		} else {
			const user : User = req.user;
			console.log('we have a query: ' + username)
			return this.usersService.findOneByUsername(user.id.toString(),username);
		}
	}

	// GET http://transcendance:8080/user?username=NomDuUser
	@UseGuards(AuthenticateGuard)
	@UseGuards(TwoFactorGuard)
	@Get('search')
	findOneByUsername(@Query('username') username: string, @Req() req) {
		const user : User = req.user;
		console.log('searching for user' + user.username);
		return this.usersService.findOneByUsername(user.id.toString(),username);
	}


	@UseGuards(AuthenticateGuard)
	@UseGuards(TwoFactorGuard)
	@Get('stats')
	getStats(@Req() request) {
		return this.usersService.getStats(request.user.id);
	}


	@UseGuards(AuthenticateGuard)
	@UseGuards(TwoFactorGuard)
	@Patch()
	async update(@Req() req, @Body(new ValidationPipe()) usersUpdateDto: UpdateUsersDto, @Res() response : Response) {
		console.log("DANS PATCH USERS");
		const user = await this.usersService.update(req.user.id, usersUpdateDto);
		// const user : User = req.user;
		if (user.isEnabledTwoFactorAuth === false && user.isTwoFactorAuthenticated === true)
			this.usersService.setIsTwoFactorAuthenticatedWhenLogout(user.id);
		console.log ("Enbale 2FA " + user.isEnabledTwoFactorAuth + " Is authenticated " + user.isTwoFactorAuthenticated);
		if (user.isEnabledTwoFactorAuth === true && user.isTwoFactorAuthenticated === false)
		{
			response.status(201).send('2FA redirect')
		}
		console.log("ON RETOURNE 200\n")
		response.status(200).send("OK")
	}

	@UseGuards(AuthenticateGuard)
	@UseGuards(TwoFactorGuard)
	@Delete()
	remove(@Req() req) {
		return this.usersService.remove(req.user.id);
	}

	@UseGuards(AuthenticateGuard)
	@UseGuards(TwoFactorGuard)
	@Post('avatar')
	@UseInterceptors(FileInterceptor('file', storageForAvatar))
	uploadAvatar(@UploadedFile() file, @Req() request){
		const user : User = request.user;
		this.usersService.updateAvatar(user.id, file.filename);
	}

	@UseGuards(AuthenticateGuard)
	@UseGuards(TwoFactorGuard)
	@Get('avatar')
	getAvatar(@Req() request, @Res() response) {
		const promise = this.usersService.getAvatarUrl(request.user.id).then((url) =>
		{
			if (url)
				return of(response.sendFile(process.cwd() + '/uploads/avatars/' + url));
			else
				throw new NotFoundException('Avatar not found');
		});
		return promise;
	}

}
