import DBResearch from "../../../types/db/DBResearch";
import { getAllResearch } from "../../db/research";
import { getUserResearch, updateUserResearch } from "../../db/users";
import User from "../User";

export type Research = {
    id: string,
    level: number,
    data: DBResearch
}

export default class ResearchManager {
    research: Array<Research> = [];
    researchDB: Array<DBResearch> = [];
    owner: User;

    constructor(user: User) {
        this.owner = user;
    }

    async init() {
        this.researchDB = await getAllResearch();
        const research = await getUserResearch(this.owner);
        this.research = research.map(r => {
            const researchData = this.researchDB.find(research => research.id === r.id);
            if(!researchData) throw new Error(`Research ${r.id} not found`);
            return {
                id: r.id,
                level: r.level,
                data: researchData
            }
        });

        return this;
    }

    getResearchById(id: string) {
        return this.research.find(research => research.data.id === id);
    }

    addResearch(research: Research) {
        const findResearch = this.research.find(r => r.data.id === research.data.id);
        if(!findResearch) this.research.push(research);
        else findResearch.level++;
    }

    async sync() {
        await updateUserResearch(this.owner, this.research.map(r => { return { id: r.data.id, level: r.level } }));
    }
}