import { ListRecordsCriteria } from '../Models';
import axios, { AxiosRequestConfig } from 'axios';
import { CachingService } from ".";

export class DynamicRecordService {
    private baseUrl: string = '';
    private _axiosRequestConfig: AxiosRequestConfig;
    private config: any = require('../config.json');
    constructor() {
        let cachingService: CachingService = new CachingService();
        this._axiosRequestConfig = {
            headers: {
                'Content-Type': 'application/json',
                'TenantId': cachingService.read('TenantId'),
                'Language': cachingService.readPersistant('Language'),
                'Authorization': 'Bearer ' + cachingService.read('Token'),
                'UserId': cachingService.read('UserId')
            }
        };
        this.baseUrl = this.config.baseUrl;
    }
    listRecords(criteria: ListRecordsCriteria): Promise<any> {
        return new Promise((resolve, reject) => {
            axios.post(this.baseUrl + '/api/DynamicObject/ListRecords', criteria, this._axiosRequestConfig).then((response) => {
                resolve(response.data);
            }, (err) => {
                reject(err);
            });
        });
    }

    getRecord(entityId: number, recordId: number): Promise<any> {
        return new Promise((resolve, reject) => {
            axios.post(this.baseUrl + '/api/DynamicObject/GetRecord', {
                entityId: entityId,
                id: recordId
            }, this._axiosRequestConfig).then((response) => {
                resolve(response.data);
            }, (err) => {
                reject(err);
            });
        });
    }

}