"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.flattenJid=flattenJid;var _fs=_interopRequireDefault(require("fs"));var _path=_interopRequireDefault(require("path"));var _baileys=require("../../Baileys");function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}let subDirs={contact:"contact/",chat:"chat/",message:"message/"};function flattenJid(jid){return jid.replace("@","-")}class StructuredStorage{bind(client){client.store=this;client.on("messaging-history.set",({chats,contacts,isLatest})=>{contactSync.call(this,{contacts,isLatest});chatSync.call(this,{chats,isLatest})});client.on("contacts.upsert",contactUpsert.bind(this));client.on("contacts.update",contactUpdate.bind(this));client.on("chats.upsert",chatUpsert.bind(this));client.on("chats.update",chatUpdate.bind(this))}searchContactByJid(jid){jid=(0,_baileys).jidNormalizedUser(jid);let file=_path.default.join(this.saveDir,subDirs.contact,flattenJid(jid));if(!_fs.default.existsSync(file))return undefined;let raw=_fs.default.readFileSync(file).toString();let data=JSON.parse(raw);return data}searchChatByJid(jid){jid=(0,_baileys).jidNormalizedUser(jid);let file=_path.default.join(this.saveDir,subDirs.chat,flattenJid(jid));if(!_fs.default.existsSync(file))return undefined;let raw=_fs.default.readFileSync(file).toString();let data=JSON.parse(raw);return data}constructor(saveDir){this.saveDir=saveDir;_fs.default.mkdirSync(saveDir,{recursive:true});saveDir+=_path.default.sep;for(const dir of Object.values(subDirs)){_fs.default.mkdirSync(_path.default.join(saveDir,dir),{recursive:true})}}}exports.StructuredStorage=StructuredStorage;function contactSync({contacts}){for(const contact of contacts){let jid=(0,_baileys).jidNormalizedUser(contact.id);let fname=flattenJid(jid);fname=_path.default.join(this.saveDir,subDirs.contact,fname);_fs.default.writeFileSync(fname,JSON.stringify(contact))}}function contactUpsert(contacts){contactSync.call(this,{contacts})}function contactUpdate(contacts){for(const contact of contacts){var ref;let data=(ref=this.searchContactByJid(contact.id))!==null&&ref!==void 0?ref:{};Object.assign(data,contact);contactSync.call(this,{contacts:[data]})}}function chatSync({chats,isLatest}){if(isLatest){let files=_fs.default.readdirSync(_path.default.join(this.saveDir,subDirs.chat));for(const each of files){_fs.default.unlinkSync(_path.default.join(this.saveDir,subDirs.chat,each))}}for(const chat of chats){_fs.default.writeFileSync(_path.default.join(this.saveDir,subDirs.chat,flattenJid((0,_baileys).jidNormalizedUser(chat.id))),JSON.stringify(chat))}}function chatUpsert(chats){chatSync.call(this,{chats,isLatest:false})}function chatUpdate(chats){for(const chat of chats){var ref;let data=(ref=this.searchChatByJid(chat.id))!==null&&ref!==void 0?ref:{};Object.assign(data,chat);contactSync.call(this,{contacts:[data]})}}function messageSync({messages,isLatest}){for(const message of messages){console.log("MESSAGE");console.dir(message)}}