import { Injectable,HttpException,HttpStatus, Res, Inject } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like, Not, ILike  } from 'typeorm';
import { classToPlain } from 'class-transformer';
import * as crypto  from 'crypto-js';

// Entities Files
import { Constants } from 'src/common/constants';
import { Configurations } from 'src/entities/configurations.entity';
import { ConfigurationsUpdateDto } from './dtos/configurations-update.dto';


// DTO Files


@Injectable()
export class ConfigurationsService {
    constructor(

        @InjectRepository(Configurations)
        private Configurations: Repository<Configurations>,

    ) {}

    async update(request : ConfigurationsUpdateDto)
    {
        if(request.request_array.length > 0){
            for await(const req of request.request_array){
                const exists = await this.Configurations.findOne({where: [{ id: req['id'] }] });
                if (exists) {
                    exists['value']  = crypto.AES.encrypt(req['value'], Constants.cryptojs_key).toString();
                    await this.Configurations.save(exists);
                }
            }
        }

        return;

    }

    async details()
    {
        let data = [];
        const datas = await this.Configurations.find({select : [ 'id', 'type', 'name', 'value' ]});
        for await(let req of datas){
            let bytes = crypto.AES.decrypt(req.value, Constants.cryptojs_key);
            req.value = bytes.toString(crypto.enc.Utf8);

            data.push(req);
        }
        // return { data : await this.Configurations.find({select : [ 'id', 'type', 'name', 'value' ]})}
        return { data : data }
    }
}
