
import Redis from 'ioredis'
import { type } from 'os'
const unflatten = require('flat').unflatten
var flatten = require('flat')
import ListWhatsAppsNumber from "../services/WhatsappService/ListWhatsAppsNumber"
import { redisConn } from './TicketCache'
import Whatsapp from "../models/Whatsapp";
import { response } from 'express'

const deleteWhatsappCache = async (hash: any) => {

    const redis: any = await redisConn();

    if (!redis) return

   //  if (redis.status !== 'connect') return

    const whatsapp_cache: any = await redis.hgetall(hash)

    try {
        if (whatsapp_cache && Object.keys(whatsapp_cache).length > 0) {

            await redis.del(hash)

            console.log(`Whatsapp cache number ${whatsapp_cache['number']} deleted!`)
        }
        else {
            console.log('WHATSAPP CACHE NOT FOUND!')
        }
    } catch (error) {
        console.log(`There was an error on deleteWhatsappCache:  ${error}`)
    }

    // await redis.quit()
}

const updateWhatsappCache = async (hash: any, json_object: any) => {

    const redis: any = await redisConn();

    if (!redis) return

   //  if (redis.status !== 'connect') return

    const pipeline = redis.pipeline()

    let entries = Object.entries(json_object)

    entries.forEach((e: any) => {
        pipeline.hset(hash, e[0], e[1])
    })

    await pipeline.exec(() => { console.log("whatsapp Key/value inserted/updated") });

    // await redis.quit()

}

const updateWhatsappCacheById = async (hash: any, update_fields: object | any) => {

    const redis: any = await redisConn();

    if (!redis) return

   //  if (redis.status !== 'connect') return

    const whatsapp_cache: any = await redis.hgetall(hash)

    try {
        if (whatsapp_cache && Object.keys(whatsapp_cache).length > 0) {

            // update_fields.escaped_name = escapeCharCache(update_fields.name)

            await updateWhatsappCache(hash, update_fields)

            console.log(`WHATSAPP ${whatsapp_cache['number']} CACHE WAS UPDATED!`)
        }
        else {
            console.log('WHATSAPP CACHE NOT FOUND!')
        }
    } catch (error) {
        console.log(`There was an error on updateWhatsappCacheById:  ${error}`)
    }

    // await redis.quit()
}

// const createOrUpdateContactCache = async (hash: any, contact: any) => {

//     const redis: any = await redisConn();

//     if(!redis) return

//    //  if (redis.status !== 'connect') return

//     if (contact.name) {
//         contact.escaped_name = escapeCharCache(contact.name)
//     }

//     await redis.hmset(hash, contact);

//     redis.quit()

// }


async function searchWhatsappCache(id: string, status: string) {

    const redis: any = await redisConn();

    if (!redis) return

   //  if (redis.status !== 'connect') return null


    const number_cache: any = await redis.hgetall(`whatsapp:${id}`)

    if (Object.entries(number_cache).length == 0) {
        // await redis.quit()
        return []
    }

    // console.log('NUMBER_CACHED: ', number_cache)

    //	@x:foo @y:bar

    const response: any = await redis.call('FT.SEARCH', 'idx_whatsapp', `(@status:*${status}*) (@number:*${number_cache.number}*)`, 'SORTBY', 'status', 'ASC')


    // await redis.quit()


    if (response.length === 1) {
        return []
    }

    const results: any = []

    for (let n = 2; n < response.length; n += 2) {
        const result: any = {}
        const fieldNamesAndValues = response[n]

        for (let m = 0; m < fieldNamesAndValues.length; m += 2) {
            const k = fieldNamesAndValues[m]
            const v = fieldNamesAndValues[m + 1]
            result[k] = v
        }

        results.push(result)
    }

    return results
}



const insertOrUpeateWhatsCache = async (hash: any, whatsapp: any) => {

    const redis: any = await redisConn();

    if (!redis) return

   //  if (redis.status !== 'connect') return

    if (Array.isArray(whatsapp)) {

        const pipeline = redis.pipeline()

        for (let i = 0; i < whatsapp.length; i++) {

            pipeline.hmset(hash, whatsapp[i]);
        }

        await pipeline.exec(() => { console.log(`${whatsapp.length} WHATSAPP INSERTED IN CACHE!`) });
    }
    else {

        await redis.hmset(hash, JSON.parse(JSON.stringify(whatsapp)));

        console.log(`WHATSAPP ID ${whatsapp.id} INSERTED OR UPADTED IN CACHE!`)

    }


    // await redis.quit()
}




const loadWhatsappCache = async () => {

    await createWhatsappIndexCache('idx_whatsapp')

    const redis: any = await redisConn();

    if (!redis) return

   //  if (redis.status !== 'connect') return

    let whatsapps: any = await Whatsapp.findAll({ raw: true })

    const pipeline = redis.pipeline()

    for (let i = 0; i < whatsapps.length; i++) {

        whatsapps[i].createdAt = new Date(whatsapps[i].createdAt).toISOString()
        whatsapps[i].updatedAt = new Date(whatsapps[i].updatedAt).toISOString()

        // whatsapps[i].escaped_name = escapeCharCache(whatsapps[i].name)

        pipeline.hmset(`whatsapp:${whatsapps[i].id}`, whatsapps[i]);
    }

    await pipeline.exec(() => { console.log(`${whatsapps.length} WHATSAPPS INSERTED IN CACHE!`) });

    // await redis.quit()
}

const createWhatsappIndexCache = async (hashIndex: string) => {

    const redis: any = await redisConn();

    if (!redis) return

   //  if (redis.status !== 'connect') return

    try {

        const lst_index_redis: any = await redis.call('FT._LIST')

        if (lst_index_redis.includes(hashIndex)) {
            console.log('entrou...')
            await redis.call('FT.DROPINDEX', hashIndex)
        }

        const response = await redis.call('FT.CREATE', hashIndex, 'ON', 'HASH', 'PREFIX', '1', 'whatsapp:', 'SCHEMA', 'id', 'NUMERIC', 'status', 'TEXT', 'SORTABLE', 'number', 'TEXT', 'SORTABLE')

        console.log('Whatsapp index created: ', response)

    } catch (error) {
        console.log('There was an error on createWhatsappIndexCache: ', error)
    }

    // await redis.quit()
}

export {
    // loadWhatsappCache,
    // searchWhatsappCache,
    // updateWhatsappCacheById,
    // insertOrUpeateWhatsCache,
    // deleteWhatsappCache
}