import { NextFunction, Request, Response } from 'express';
import logging from '../../config/logging';
import config from '../../config/config';
const mysql = require('mysql');
const util = require('util');
import header from '../../middleware/apiHeader';
import { ResultSuccess } from '../../classes/response/resultsuccess';
import { ResultError } from '../../classes/response/resulterror';
import path from 'path';

let 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 beginTransaction = util.promisify(connection.beginTransaction).bind(connection);
const commit = util.promisify(connection.commit).bind(connection);
const rollback = util.promisify(connection.rollback).bind(connection);

const NAMESPACE = 'Languages';

const getlanguages = async (req: Request, res: Response, next: NextFunction) => {
    try {
        logging.info(NAMESPACE, 'Getting Languages');
        let startIndex = req.body.startIndex ? req.body.startIndex : 0;
        let fetchRecord = req.body.fetchRecords ? req.body.fetchRecords : 0;
        let countSql = "SELECT COUNT(*) as totalCount  FROM languages";
        let sql = "SELECT * FROM languages";
        if (startIndex >= 0 && fetchRecord > 0) {
            sql += " LIMIT " + fetchRecord + " OFFSET " + startIndex + " ";
        }
        let countResult = await query(countSql);
        let result = await query(sql);
        if (result && result.length > 0) {
            let successResult = new ResultSuccess(200, true, 'Get Languages Successfully', result, countResult[0].totalCount);
            console.log(successResult);
            return res.status(200).send(successResult);
        }
        if (result) {
            let successResult = new ResultSuccess(200, true, "Get Languages Successfully", [], 0);
            return res.status(200).send(successResult);
        } else {
            let errorResult = new ResultError(400, true, "language.getlanguages() Error", result, '');
            next(errorResult);
        }
    } catch (error) {
        let errorResult = new ResultError(500, true, 'language.getlanguages() Exception', error, '');
        next(errorResult);
    }
};

const insertUpdateLanguage = async (req: Request, res: Response, next: NextFunction) => {
    try {
        logging.info(NAMESPACE, 'Inserting Language');
        let requiredFields = ['language', 'code'];
        let validationResult = header.validateRequiredFields(req, requiredFields);
        if (validationResult && validationResult.statusCode == 200) {
            let authorizationResult = await header.validateAuthorization(req, res, next);
            if (authorizationResult.statusCode == 200) {
                let currentUser = authorizationResult.currentUser;
                let name = req.body.language;
                let id = req.body.id;
                let userId = currentUser.id;
                let checkSql = `SELECT * FROM languages WHERE LOWER(language) = '` + name.toLowerCase() + `'`;
                if (id) {
                    checkSql += ` AND id != ` + id;
                }
                let checkResult = await query(checkSql);
                if (checkResult && checkResult.length > 0) {
                    let errorResult = new ResultError(400, true, "", new Error("Language Already Exist"), '');
                    next(errorResult);
                } else {
                    let updateResult;
                    if (req.body.id > 0) {
                        let updateSql = `UPDATE languages SET language = '` + name + `', code = '` + req.body.code.toLowerCase() + `' WHERE id = ` + id;
                        updateResult = await query(updateSql);
                        if (updateResult && updateResult.affectedRows >= 0) {
                            // let successResult = new ResultSuccess(200, true, 'Update Language', updateResult, 1);
                            // return res.status(200).send(successResult);
                        }
                    }
                    else {
                        let sql = `INSERT INTO languages(language,code) VALUES('` + name + `','` + req.body.code.toLowerCase() + `'); `
                        updateResult = await query(sql);
                        // let successResult = new ResultSuccess(200, true, 'Insert Language ', result, 1);
                        // return res.status(200).send(successResult);
                    }
                    const fs = require('fs');
                    const fileName = req.body.code.toLowerCase() + '.json';
                    const filePath = path.join(__dirname, '../../../client/src/assets/admin/i18n/', fileName);
                    if (!fs.existsSync(filePath)) {
                        const initialData = {
                            key: 'value',
                        };

                        // Write the initial data to the file
                        fs.writeFileSync(filePath);
                        console.log('File created successfully.');
                    } else {
                        console.log('File already exists.');
                    }
                    let successResult = new ResultSuccess(200, true, 'Update Language', updateResult, 1);
                    return res.status(200).send(successResult);
                }
            } else {
                let errorResult = new ResultError(401, true, "Unauthorized request", authorizationResult, '');
                next(errorResult);
            }
        } else {
            let errorResult = new ResultError(validationResult.statusCode, true, validationResult.message, new Error(validationResult.message), '');
            next(errorResult);
        }
    } catch (error) {
        let errorResult = new ResultError(500, true, 'Language.insertUpdateLanguage() Exception', error, '');
        next(errorResult);
    }
};

const activeInactiveLanguage = async (req: Request, res: Response, next: NextFunction) => {
    try {
        logging.info(NAMESPACE, 'Active Inactive Language');
        let requiredFields = ['id'];
        let validationResult = header.validateRequiredFields(req, requiredFields);
        if (validationResult && validationResult.statusCode == 200) {
            let authorizationResult = await header.validateAuthorization(req, res, next);
            if (authorizationResult.statusCode == 200) {
                let currentUser = authorizationResult.currentUser;
                let id = req.body.id;
                let userId = currentUser.id;
                let isActive = req.body.isActive ? req.body.isActive : '!isActive'
                if (req.body.id > 0) {
                    let sql = "UPDATE languages SET isActive = " + isActive + " WHERE id = " + id;
                    let result = await query(sql);
                    if (result && result.affectedRows >= 0) {
                        let successResult = new ResultSuccess(200, true, 'Update Language', result, 1);
                        return res.status(200).send(successResult);
                    }
                }
                console.log(result);
                var result = await query(result);
                let successResult = new ResultSuccess(200, true, 'Update Language', result, 1);
                return res.status(200).send(successResult);

            } else {
                let errorResult = new ResultError(401, true, "Unauthorized request", authorizationResult, '');
                next(errorResult);
            }
        } else {
            let errorResult = new ResultError(validationResult.statusCode, true, validationResult.message, new Error(validationResult.message), '');
            next(errorResult);
        }
    } catch (error) {
        let errorResult = new ResultError(500, true, 'language.activeInactiveLanguage() Exception', error, '');
        next(errorResult);
    }
};

export default { getlanguages, insertUpdateLanguage, activeInactiveLanguage };