import React from 'react';

import  API from './API';

class Repository {
    constructor(tablename, token , filters = []) {
        this.tablename = tablename;
        this.token = token;
        this.filters = filters.map((item) => { return {...item, options: item.values}});
        this.API = new API('/' + this.tablename, token);
        this.renderFilters();

    }

    setToken(token) {
        this.API.token = token;
        this.token = token;
    }

    setFilters(fil) {
        if(!fil)return;
        this.filters = fil;
        this.renderFilters();
    }

    renderFilters(){
        let fils = [];
        this.filters.forEach((item)=> {
            if(item.values && item.values.length || ["ascending", "descending"].includes(item.type)){
               fils.push(item);
            }
        })
        this.renderedFilters = JSON.stringify(fils);  
    }

    count() {
        return this.API.get(`/count?filters=${this.renderedFilters}`);
    }

    getPage(page, perPage = 10) {
        return this.API.get(`?page=${page}&perPage=${perPage}&filters=${this.renderedFilters}`);
    }

    get(id) {
        return this.API.get('/' + id);
    }

    update(id, obj) {
        return this.API.put('/' + id, obj);
    }

    add(obj) {
        return this.API.post('', obj);
    }

    delete(id) {
        return this.API.delete('/' + id);
    }

    import(data) {
        return this.API.post('/import', data);
    }

    model() {
        return this.API.get('/Model');
    }
}

export default Repository;