import config from '../config/config';
const mysql = require('mysql');
const util = require('util');
const AWS = require('aws-sdk');

var connection = mysql.createConnection({
    host: config.mysql.host,
    user: config.mysql.user,
    password: config.mysql.pass,
    database: config.mysql.database
})

const query = util.promisify(connection.query).bind(connection);
const NAMESPACE = 'Store Image';
const fs = require('fs');

const storeImage = async (keyName: string, fileExt: string, buf: any, contentType, bucketName: string, oldImage) => {
    try {
        let awsKey = await query(`SELECT * FROM systemflags`);
        let imageUrl;
        let errorwhenuploadImage;
        if (awsKey.find(c => c.name == 'isUseAwsBucket').value == true) {
            const S3 = new AWS.S3({
                accessKeyId: awsKey.find(c => c.name == 'AWS_ID').value,
                secretAccessKey: awsKey.find(c => c.name == 'AWS_SECRET').value,
                region: awsKey.find(c => c.name == 'region').value,
            });
            let defaultName = awsKey.find(c => c.name == 'bucketDefaultName').value;
            let params = {
                Bucket: bucketName,
                Key: keyName + "_" + new Date().getTime() + "." + fileExt,
                Body: buf,
                ContentEncoding: 'base64',
                ContentType: contentType,
                ACL: 'public-read'
            };
            if (oldImage) {
                if (oldImage.includes("https")) {
                    let splt = oldImage.split("/");
                    await S3.deleteObject({
                        Bucket: bucketName,
                        Key: splt[splt.length - 1],
                    });
                }
                else {
                    fs.unlink('./' + oldImage, (err: any) => {
                        if (err) throw err;
                    });
                }
            }
            const s3Response = await S3.upload(params).promise();

            if (s3Response.Location) {
                return s3Response.Location;
            }
            else {
                return false;
            }
        }
        else {
            let dir = './content';
            if (!fs.existsSync(dir)) {
                fs.mkdirSync(dir);
            }

            let dir1 = './content/' + bucketName;
            if (!fs.existsSync(dir1)) {
                fs.mkdirSync(dir1);
            }
            const fileContentsUser = Buffer.from(buf, 'base64');
            let imagePath = "content/" + bucketName + "/" + new Date().getTime() + "." + fileExt;
            const writeFile = util.promisify(fs.writeFile);
            try {
                await writeFile('./' + imagePath, fileContentsUser);
                if (oldImage) {
                    if (oldImage.includes("https")) {
                        let splt = oldImage.split("/");
                        const S3 = new AWS.S3({
                            accessKeyId: awsKey.find(c => c.name == 'AWS_ID').value,
                            secretAccessKey: awsKey.find(c => c.name == 'AWS_SECRET').value,
                            region: awsKey.find(c => c.name == 'region').value,
                        });
                        await S3.deleteObject({
                            Bucket: bucketName,
                            Key: splt[splt.length - 1],
                        });
                    }
                    else {
                        fs.unlink('./' + oldImage, (err: any) => {
                            if (err) throw err;
                        });
                    }
                }
                return imagePath;
            } catch (error) {
                return false;
            }
            //     , (err: any) => {
            //     if (err)
            //         return false
            //     else {
            //         if (oldImage) {
            //             if (fs.existsSync('./' + oldImage)) {
            //                 fs.unlink('./' + oldImage, (err: any) => {
            //                     if (err) throw err;
            //                     console.log(imagePath + ' was deleted');
            //                 });
            //             }
            //         }
            //         return imagePath;

            //     };
            // });
            // const filePath = await fs.writeFile(imagePath, fileContentsUser, (err: any) => {
            //     if (err)
            //         errorwhenuploadImage = err;
            //     else {
            //         if (oldImage) {
            //             if (fs.existsSync('./' + oldImage)) {
            //                 fs.unlink('./' + oldImage, (err: any) => {
            //                     if (err) throw err;
            //                     console.log(imagePath + ' was deleted');
            //                 });
            //             }
            //         }
            //         // imageUrl = imagePath;

            //     }
            // });
            //    return filePath;
        }
    } catch (error) {
        return false;
    }

};

// const getImage = async (key: any, filePath: string) => {
//     try {
//         const getParams = {
//             Bucket: 'government-docs',
//             Key: key,
//         };
//         const data = await config.s3bucket.getObject(getParams).promise();
//         let bufferData = data.Body;
//         await fs.writeFile('./' + filePath, bufferData, async (err: any) => {
//             if (err) {
//                 return false;
//             } else {
//                 return true;
//             }
//         });

//     } catch (error: any) {
//         return false;
//     }
// }

export default { storeImage };