import { User, Country } from '../Models';
import axios, { AxiosPromise, AxiosRequestConfig } from 'axios';
import { CachingService } from ".";

export class UserService {
    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'),
                'Bearer': cachingService.read('Token')
            }
        };
        this.baseUrl = this.config.baseUrl;
    }

    getUser(id: string): AxiosPromise<Response> {
        return axios.get(this.baseUrl + '/api/User/GetUser/' + id, this._axiosRequestConfig)
    }
    deleteUser(id: string): AxiosPromise<Response> {
        return axios.get(this.baseUrl + '/api/User/DeleteUser/' + id, this._axiosRequestConfig)
    }
    listUsers(): Promise<User[]> {
        return new Promise((resolve, reject) => {
            axios.post(this.baseUrl + '/api/User/ListUsers', null, this._axiosRequestConfig).then((response) => {
                resolve(response.data);
            }, (err) => {
                reject(err);
            });
        });
    }
    searchUsers(searchTerm: string): Promise<User[]> {
        return new Promise((resolve, reject) => {
            axios.get(this.baseUrl + '/api/User/SearchUsers?searchTerm=' + searchTerm, this._axiosRequestConfig).then((response) => {
                resolve(response.data);
            }, (err) => {
                reject(err);
            });
        });
    }
    listOrganizationUsers(organizationUnitId: number): Promise<User[]> {
        return new Promise((resolve, reject) => {
            axios.get(this.baseUrl + '/api/User/ListOrganizationUsers?organizationUnitId=' + organizationUnitId, this._axiosRequestConfig).then((response) => {
                resolve(response.data);
            }, (err) => {
                reject(err);
            });
        });
    }
    saveUser(user: User): AxiosPromise<Response> {
        return axios.post(this.baseUrl + '/api/User/SaveUser', user, this._axiosRequestConfig)
    }
    listCountries(): Promise<Country[]> {
        return new Promise((resolve, reject) => {
            axios.get(this.baseUrl + '/api/User/ListCountries', this._axiosRequestConfig).then((response) => {
                resolve(response.data);
            }, (err) => {
                reject(err);
            });
        });
    }
}