import { BaseDataStore } from '../lib/db/DataStore';
import { BaseDto, ObjectStore } from '../lib/db/DBAccess';
import { LongAsyncRemoteFunction } from '../lib/objectTransport/LongAsyncRemoteFunction';

declare global {
    interface Window { tests: any; }
}

class PersonDto implements BaseDto {
    id?: string;

    name: string;
    university: string;

    constructor(_name: string, _university: string) {
        this.name = _name;
        this.university = _university;
    }

    static get dbName(): string {
        return 'Persons';
    }
}

class UniversityDto implements BaseDto {
    id?: string;

    name: string;
    constructor(_name: string) {
        this.name = _name;
    }

    static get dbName(): string {
        return 'Universities';
    }
}

interface UniversityStoreFunctionMap {
    'createUniversity': { name: string }
}


class UniversityDataStore extends BaseDataStore {
    private _personDao?: ObjectStore<PersonDto>;
    private _universityDao?: ObjectStore<UniversityDto>;
    private larf?: LongAsyncRemoteFunction<UniversityStoreFunctionMap>;


    protected async init(): Promise<void> {
        this._personDao = await this.getDao(PersonDto);
        this._universityDao = await this.getDao(UniversityDto);
        this.larf = this.getLarf('test');
        this.larf.register('createUniversity', this.createUniversity.bind(this));
    }

    async createUniversity(fromId: string, { name }: UniversityStoreFunctionMap['createUniversity']): Promise<void> {
        await this._universityDao!.add(new UniversityDto(name));
    }

    async createPerson(name: string, university: string): Promise<PersonDto> {
        return await this._personDao!.add(new PersonDto(name, university));
    }

    async getPerson(id: string): Promise<PersonDto | undefined> {
        return await this._personDao!.get(id);
    }

    async getUniversity(id: string): Promise<UniversityDto | undefined> {
        return await this._universityDao!.get(id);
    }
}