import { Config, cfg } from "./Config";
import { request_data } from "./DataRequester";

export class Database {
    private db: Datapoint[] = [];

    constructor() {
        let groups = Object.keys(cfg);
        groups.forEach(group => {
            let members = Object.keys(cfg[group]);
            members.forEach(member => {
                if((member != "text") && (member != "uri")) {
                    this.add(cfg[group][member])
                }
            });
        });
    }

    add(id: string, value?: string, type?: string): void {
        let found: boolean = false;
        this.db.forEach(element => {
                if(element.id == id) {
                    element.value = value;
                    element.type = type
                    found = true;
                }
        });
        if(!found) {
            this.db.push(new Datapoint(id, value, type));
        }
    }

    get(id: string): string {
        for(const el of this.db) {
            if(el.id == id) {
                return el.value;
            }
        }
        return null;
    }

    start(): void {
        setInterval(this.cyclic_requets, 1000, this);
    }

    cyclic_requets(self: &Database): void {
            self.db.forEach(element => {
                request_data(element.id, self)
        });
    }
}

class Datapoint {
    id: string;
    value: string;
    type: string;

    constructor(id: string, value: string, type: string) {
        this.id = id;
        this.type = type;
        this.value = value;
    }
}
