import { Body, Controller, Delete, Get, HttpException, HttpStatus, Param, Post, Put, Query, Res, UploadedFiles, UseGuards, Headers, UseInterceptors } from '@nestjs/common';
import { ApiBearerAuth, ApiBody, ApiConsumes, ApiParam, ApiTags } from '@nestjs/swagger';
import { Response } from 'express';
import { JwtAuthGuard } from '../../guards/auth/jwt-auth.guard';
import { SignupDto, UserUpdateDto,LoginDto,ForgotDto,editFileName,AddRoleDto, CreateClientDto, UpdateClientDto, CreateVendorDto } from './dto/users.dto';
import { UsersService } from './users.service';
import { FilesInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
const axios = require("axios").default;

@Controller('users')
@ApiTags('User')
export class UsersController {
    constructor(private readonly userService: UsersService) { }
    
    @Get('/')
    // @UseGuards(JwtAuthGuard)
    getUsers() {
        try {
            return this.userService.getUsers();
        } catch (ex) {
            ex;
        }
       
    }

   
   

    @Get('/:id')
    // @UseGuards(JwtAuthGuard)
    async getUser(@Param('id') id: number,@Res() res?: Response) {
        try {
            if (!id) throw new HttpException('Please enter a valid id', HttpStatus.BAD_REQUEST)
        var response = await this.userService.getUser(id);
        if(response){
          return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"User detail",data:response});
          }else{
          return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:""});
          }
        } catch (ex) {
          ex;  
        }
        
    }


    @Post('/register')
  
    async register(@Body() data: SignupDto,@Headers() headers: Headers,@Res() res?: Response) {
        try {
            var response = await this.userService.register(data);
            if(response == "alreadyexist"){
              return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"User Already Exist",data:"User Already Exist"});
          }else{
              return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"User has been registered successfully",data:"User has been registered successfully"});
          }
        } catch (ex) {
            throw ex;
        }
    }

    @Put('/:id')
    // @UseGuards(JwtAuthGuard)
    @UseInterceptors(
      FilesInterceptor('name', 20, {
        storage: diskStorage({
          destination: './media',
          filename: editFileName,
        }),
      }),
    )
    @ApiConsumes('multipart/form-data')
    @ApiBody({
      schema: {
        type: 'object',
        properties: {
          full_name :{
            type: 'string'
          }, 
          designation: {
            type: 'string'
          },
          client_id :{
            type: 'number'
          },
          project_id :{
            type: 'number'
          },
          city: {
            type: 'string'

          },
          location: {
            type: 'string'

          },
          nationality: {
            type: 'string'

          },
          job_title: {
            type: 'string'

          },
          job_type: {
            type: 'string'

          },
          contact_no: {
            type: 'string'

          },
          
          name: { // 👈 this property
            type: 'string',
            format: 'binary',
          },
        },
      },
    })
   async updateUser(@Param('id') id: number,@Body() mydata:UserUpdateDto,@UploadedFiles() files,@Headers() headers: Headers,@Res() res: Response) {
        try {
          console.log(mydata)
            if (!id) throw new HttpException('Please enter a valid id', HttpStatus.BAD_REQUEST)
            var response =  await this.userService.update(id,mydata,files);
        if(response){
          return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"User has been updated successfully",data:response});
          }else{
          return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:""});
          }
        } catch (ex) {
            throw ex;
        }
        
    }

    @Put('/assignDepartment/:user_id/')
    
    @ApiBody({
      schema: {
        type: 'object',
        properties: {
         
          department_id: {
            type: 'number'
          },


        },
      },
    })

   async assign(@Param('user_id') user_id: number,@Body() reqested:UserUpdateDto,@Headers() headers: Headers,@Res() res: Response) {
        try {
            if (!user_id) throw new HttpException('Please enter a valid id', HttpStatus.BAD_REQUEST)
        if(res){
          var mydata = await this.userService.assign(user_id,reqested);         

          return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"Assigned Department to User been updated successfully",data:mydata});

          }else{
          return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:""});
          }
        } catch (ex) {
            throw ex;
        }
        
    }

    @ApiBody({
      schema: {
        type: 'object',
        properties: {
          userId :{
              type: 'number'
            },
            OTPCode :{
            type: 'string'
          },
        },
      },
    })
    @Post('/verifyOTP')
    async verifyOTP(@Body() data,@Res() res?: Response) {
      try {
        var mydata  = await this.userService.verifyOTP(data);
        if(mydata == "expired"){
          data = {
            status: false,
            message: "OTP is expired try again",
            data: "",
            error: true,
            isVerified:0
          }
        return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"OTP has been expired",data:data});
        }else if(mydata == "notfound"){
          data = {
            status: false,
            message: "User Not found",
            data: "",
            error: true,
            isVerified: 0
          }
          return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"user not found",data:data});
        }else{
        return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"Logged in successfully",data:mydata});
        }
    } catch (ex) {
        return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:ex});

    }
  }

    @Post('/login')
    login(@Body() data: LoginDto) {  
        try {
            return this.userService.login(data.email, data.password, data.phoneNo);
        } catch (ex) {
            throw ex;
        }
    }


    @Post('/forgotPassword')
    async forgotPassword(@Body() data: ForgotDto,@Res() res?: Response) {  
        try {
            var mydata  = await this.userService.forgotPassword(data.email,data.password);
            if(mydata == "invalid"){
            return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:"Invalid Email"});
            }else{
            return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"Password has been changed successfully",data:""});
            }
        } catch (ex) {
            return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:ex});
  
        }
    }

    @Post('/role')
  
    async addRole(@Body() data: AddRoleDto,@Headers() headers: Headers,@Res() res?: Response) {
        try {
            var response = await this.userService.addRole(data);
            if(response == "alreadyexist"){
              return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"Role Already Exist",data:"Role Already Exist"});
          }else{
              return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"Role has been added successfully",data:"Role has been added successfully"});
          }
        } catch (ex) {
            throw ex;
        }
    }
   
    @Get('/roles/all')
    // @UseGuards(JwtAuthGuard)
    async getRoles(@Res() res?: Response) {
        try {
           var response = await this.userService.getRoles();
        if(response){
          return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"All Roles ",data:response});
          }else{
          return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:""});
          }
        } catch (ex) {
          ex;  
        }
        
    }
    


    @Get('/role/:id')
    // @UseGuards(JwtAuthGuard)
    async getRole(@Param('id') id: number,@Res() res?: Response) {
        try {
            if (!id) throw new HttpException('Please enter a valid id', HttpStatus.BAD_REQUEST)
        var response = await this.userService.getRole(id);
        if(response){
          return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"Role detail",data:response});
          }else{
          return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:""});
          }
        } catch (ex) {
          ex;  
        }
        
    }

    @Put('/assignRole/:user_id/')
    
    @ApiBody({
      schema: {
        type: 'object',
        properties: {
         
          role_id: {
            type: 'number'
          }

        },
      },
    })

   async assignRole(@Param('user_id') user_id: number,@Body() reqested:UserUpdateDto,@Headers() headers: Headers,@Res() res: Response) {
        try {
            if (!user_id) throw new HttpException('Please enter a valid id', HttpStatus.BAD_REQUEST)
        if(res){
          var mydata = await this.userService.assignRole(user_id,reqested);         

          return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"User role has been updated successfully",data:mydata});

          }else{
          return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:""});
          }
        } catch (ex) {
            throw ex;
        }
        
    }

    



 
   

    

 

    @Get('/client/all')
    // @UseGuards(JwtAuthGuard)
    async getClients(@Res() res?: Response) {
        try {
           var response = await this.userService.getClients();
        if(response){
          return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"All Clients ",data:response});
          }else{
          return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:""});
          }
        } catch (ex) {
          ex;  
        }
        
    }

    @Get('/client/:id')
    // @UseGuards(JwtAuthGuard)
    async getClientUser(@Param('id') id: number,@Res() res?: Response) {
        try {
            if (!id) throw new HttpException('Please enter a valid id', HttpStatus.BAD_REQUEST)
        var response = await this.userService.getClientUser(id);
        if(response){
          return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"Client User detail",data:response});
          }else{
          return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:""});
          }
        } catch (ex) {
          ex;  
        }
        
    }

    @Get('/vendor/:id')
    // @UseGuards(JwtAuthGuard)
    async getVendorUser(@Param('id') id: number,@Res() res?: Response) {
        try {
            if (!id) throw new HttpException('Please enter a valid id', HttpStatus.BAD_REQUEST)
        var response = await this.userService.getVendorUser(id);
        if(response){
          return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"Vendor User detail",data:response});
          }else{
          return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:""});
          }
        } catch (ex) {
          ex;  
        }
        
    }

  


    @Post('/client/add')
    @ApiBody({
        schema: {
          type: 'object',
          properties: {
            client_name :{
              type: 'string'
            },
            user_id :{
              type: 'number'
            },
            project_id :{
              type: 'number'
            }           
          },
        },
      })
    async add(@Body() data: CreateClientDto,@Headers() headers: Headers,@Res() res?: Response) {
        try {
            var response = await this.userService.add(data);
            if(response == "alreadyexist"){
              return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"Client Already Exist",data:"Client Already Exist"});
          }else{
              return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"Client has been added successfully",data:"Client has been added successfully"});
          }
        } catch (ex) {
            throw ex;
        }
    }

    @Put('/client/:id')
    
   async updateClient(@Param('id') id: number,@Body() mydata:UpdateClientDto,@Headers() headers: Headers,@Res() res: Response) {
        try {
          console.log(id)
            if (!id) throw new HttpException('Please enter a valid id', HttpStatus.BAD_REQUEST)
            var response =  await this.userService.updateClient(id,mydata);
           
        if(response){
          return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"Client User has been updated successfully",data:response});
          }else{
          return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:""});
          }
        } catch (ex) {
            throw ex;
        }
        
    }

    @Post('/vendor/add')
    @ApiBody({
        schema: {
          type: 'object',
          properties: {
            vendor_name :{
              type: 'string'
            },
            user_id :{
              type: 'number'
            },
          
          },
        },
      })
   
    async addVendor(@Body() data: CreateVendorDto,@Headers() headers: Headers,@Res() res?: Response) {
      try {
          var response = await this.userService.addVendor(data);
          if(response == "alreadyexist"){
            return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"Vendor Already Exist",data:"Vendor Already Exist"});
        }else{
            return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"Vendor has been added successfully",data:"Vendor has been added successfully"});
        }
      } catch (ex) {
          throw ex;
      }
  }
    @Put('/vendor/:id')
    // @UseGuards(JwtAuthGuard)
    
    @ApiBody({
      schema: {
        type: 'object',
        properties: {
          vendor_name :{
            type: 'string'
          },
          user_id :{
            type: 'number'
          },
         },
      },
    })

   async updateVendor(@Param('id') id: number,@Body() mydata,@Headers() headers: Headers,@Res() res: Response) {
        try {
            if (!id) throw new HttpException('Please enter a valid id', HttpStatus.BAD_REQUEST)
            var response =  await this.userService.updateVendor(id,mydata);
        if(response){
          return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"Vendor User has been updated successfully",data:response});
          }else{
          return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:""});
          }
        } catch (ex) {
            throw ex;
        }
        
    }

    @ApiBearerAuth('jwt')
    // @UseGuards(JwtAuthGuard)
    @Delete('/vendor/:id')
    async deleteVendor(@Param('id') id: number,@Res() res: Response) {
        try {
            if (!id) throw new HttpException('Please enter a valid id', HttpStatus.BAD_REQUEST)
            var execute_delete_query = await this.userService.deleteVendor(id);
          if(execute_delete_query == "deleted"){
            return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"Vendor Account has been deleted",data:"Vendor Account has been deleted"});
            }else{
            return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:""});
            }
        } catch (ex) {
            throw ex;
        }
    }


    @ApiBearerAuth('jwt')
    // @UseGuards(JwtAuthGuard)
    @Delete('/:id')
    async deleteUser(@Param('id') id: number,@Res() res: Response) {
        try {
            if (!id) throw new HttpException('Please enter a valid id', HttpStatus.BAD_REQUEST)
            var execute_delete_query = await this.userService.deleteUser(id);
          if(execute_delete_query == "deleted"){
            return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"Account has been deleted",data:"Account has been deleted"});
            }else{
            return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:""});
            }
        } catch (ex) {
            throw ex;
        }
    }

    @ApiBearerAuth('jwt')
    // @UseGuards(JwtAuthGuard)
    @Delete('/client/:id')
    async deleteClient(@Param('id') id: number,@Res() res: Response) {
        try {
            if (!id) throw new HttpException('Please enter a valid id', HttpStatus.BAD_REQUEST)
            var execute_delete_query = await this.userService.deleteClient(id);
          if(execute_delete_query == "deleted"){
            return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"Client Account has been deleted",data:"Client Account has been deleted"});
            }else{
            return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:""});
            }
        } catch (ex) {
            throw ex;
        }
    }

    

   

 //   @Post('/addAttendance')
  //   @UseInterceptors(
  //     FilesInterceptor('name', 20, {
  //       storage: diskStorage({
  //         destination: './media',
  //         filename: editFileName,
  //       }),
  //     }),
  //   )
  //   @ApiConsumes('multipart/form-data')
  //   @ApiBody({
  //     schema: {
  //       type: 'object',
  //       properties: {
  //         user_id :{
  //           type: 'number'
  //         },
  //         request_type :{
  //           type: 'string',
  //           description: "clockout,clockin,checkout,checkin",
  //         },
  //         name: { // 👈 this property
  //           type: 'string',
  //           format: 'binary',
  //         },
  //       },
  //     },
  //   })
  //   async addAttendance(@Body() data,@UploadedFiles() files,@Res() res?: Response) {  
  //     try {
  //       if (!data.user_id) throw new HttpException('Please enter a user id', HttpStatus.BAD_REQUEST)
  //         var mydata  = await this.userService.addAttendance(data,files);
  //         if(mydata == "invalid"){
  //         return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:"Invalid Data"});
  //         }else{
  //         return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"Attendance has been updated",data:""});
  //         }
  //     } catch (ex) {
  //         return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:ex});

  //     }
  // }


  // @Get('/getAttendance/:userId/:attendanceDate')
  //   // @UseGuards(JwtAuthGuard)
  //   getAttendance(@Param('userId') userId: number,@Param('attendanceDate') attendanceDate: string) {
  //       try {
  //           if (!userId) throw new HttpException('Please enter a valid id', HttpStatus.BAD_REQUEST)
  //       return this.userService.getAttendance(userId,attendanceDate);
  //       } catch (ex) {
  //         ex;  
  //       }
        
  //   }

    // @Get('/getAllAttendance/:start_date/:end_date')
    // @ApiParam({
    //   name: "start_date",
    //   required: false
    // })
    // @ApiParam({
    //   name: "end_date",
    //   required: false
    // })
    // // @UseGuards(JwtAuthGuard)
    // getAllAttendance(@Param('start_date') start_date: string,
    // @Param('end_date') end_date: string) {
    //     try {
    //     return this.userService.getAllAttendance(start_date,end_date);
    //     } catch (ex) {
    //       ex;  
    //     }
        
    // }




    // @Get('/userActivityCount/:userId')
    // // @UseGuards(JwtAuthGuard)
    // userActivityCount(@Param('userId') userId: number) {
    //     try {
    //         if (!userId) throw new HttpException('Please enter a valid id', HttpStatus.BAD_REQUEST)
    //     return this.userService.userActivityCount(userId);
    //     } catch (ex) {
    //       ex;  
    //     }
        
    // }

  //   @Post('/addCheckList')
  //   @ApiBody({
  //     schema: {
  //       type: 'object',
  //       properties: {
  //         name :{
  //           type: 'string'
  //         },
  //         description :{
  //           type: 'string'
  //         }
  //       },
  //     },
  //   })
  //   async addCheckList(@Body() data,@Res() res?: Response) {  
  //     try {
        
  //         var mydata  = await this.userService.addCheckList(data);
  //         if(mydata == "invalid"){
  //         return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:"Invalid Data"});
  //         }else{
  //         return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"Data has been added",data:""});
  //         }
  //     } catch (ex) {
  //         return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:ex});

  //     }
  // }


  // @Post('/addUserCheckList')
  //   @UseInterceptors(
  //     FilesInterceptor('name', 20, {
  //       storage: diskStorage({
  //         destination: './media',
  //         filename: editFileName,
  //       }),
  //     }),
  //   )
  //   @ApiConsumes('multipart/form-data')
  //   @ApiBody({
  //     schema: {
  //       type: 'object',
  //       properties: {
  //         check_list_id: {
  //           type: 'array', // 👈  array of services
  //           items: {
  //             type: 'number'
  //           },
  //         },
  //         vehicle_name :{
  //           type: 'string'
  //         },
  //         plate_number :{
  //           type: 'string'
  //         },
  //         remarks :{
  //           type: 'string'
  //         },
  //         user_id :{
  //           type: 'number'
  //         },
  //         name: { // 👈 this property
  //           type: 'string',
  //           format: 'binary',
  //         },
  //       },
  //     },
  //   })
  //   async addUserCheckList(@Body() data,@UploadedFiles() files,@Res() res?: Response) {  
  //     try {
  //       if (!data.user_id) throw new HttpException('Please enter a user id', HttpStatus.BAD_REQUEST)
  //         var mydata  = await this.userService.addUserCheckList(data,files);
  //         if(mydata == "invalid"){
  //         return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:"Invalid Data"});
  //         }else if(mydata == "already"){
  //           return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Data already added for existing user and date",data:"already added"});
  //           }else{
  //         return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"Data has been added",data:""});
  //         }
  //     } catch (ex) {
  //         return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:ex});

  //     }
  // }


  // @Get('/checklist/getChecklist')
  //   // @UseGuards(JwtAuthGuard)
  //   async getChecklist(@Res() res?: Response) {
  //       try {
  //       var response = await this.userService.getChecklist();
  //       if(response){
  //         return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"Check list detail",data:response});
  //         }else{
  //         return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:""});
  //         }
  //       } catch (ex) {
  //         ex;  
  //       }
        
  //   }

  //   @Get('/checklist/getUserChecklist/:id/:checklist_date')
  //   // @UseGuards(JwtAuthGuard)
  //   async getUserChecklist(@Param('id') id: number,@Param('checklist_date') checklist_date:string,@Res() res?: Response) {
  //       try {
  //           if (!id) throw new HttpException('Please enter a valid id', HttpStatus.BAD_REQUEST)
  //       var response = await this.userService.getUserChecklist(id,checklist_date);
  //       if(response){
  //         return res.status(HttpStatus.OK).json({statusCode:res.statusCode,statusMessage:"User Checklist detail",data:response});
  //         }else{
  //         return res.status(HttpStatus.BAD_REQUEST).json({statusCode:res.statusCode,statusMessage:"Something went wrong",data:""});
  //         }
  //       } catch (ex) {
  //         ex;  
  //       }
        
  //   }


 






}
