import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from '../../../../environments/environment';
import { DataTableRequest } from '../../model/data-table/data-table-request';
import { DmpProfile } from '../../model/dmp-profile/dmp-profile';
import { BaseHttpService } from '../http/base-http.service';
import { DmpProfileListing } from '../../model/dmp-profile/dmp-profile-listing';
import { RequestItem } from '../../query/request-item';
import { DataTableData } from '../../model/data-table/data-table-data';
import { DmpProfileCriteria } from '../../query/dmp/dmp-profile-criteria';
import { DatasetListingModel } from '../../model/dataset/dataset-listing';
import { BaseHttpParams } from '../../../../common/http/base-http-params';
import { InterceptorType } from '../../../../common/http/interceptors/interceptor-type';
import { DmpProfileExternalAutocompleteCriteria } from '../../query/dmp/dmp-profile-external-autocomplete-criteria';
import { ConfigurationService } from '../configuration/configuration.service';

@Injectable()
export class DmpProfileService {

	private actionUrl: string;
	private headers = new HttpHeaders();

	constructor(private http: BaseHttpService, private httpClient: HttpClient, private configurationService: ConfigurationService) {
		this.actionUrl = configurationService.server + 'dmpprofile/';
	}

	getPaged(dataTableRequest: DataTableRequest<DmpProfileCriteria>): Observable<DataTableData<DmpProfileListing>> {
		return this.http.post<DataTableData<DmpProfileListing>>(this.actionUrl + 'getPaged', dataTableRequest, { headers: this.headers });
	}

	getSingle(id: String): Observable<DmpProfile> {
		return this.http.get<DmpProfile>(this.actionUrl + 'getSingle/' + id, { headers: this.headers });
	}

	createDmp(dataManagementPlanModel: DmpProfile): Observable<DmpProfile> {
		return this.http.post<DmpProfile>(this.actionUrl, dataManagementPlanModel, { headers: this.headers });
	}

	public downloadXML(id: string): Observable<HttpResponse<Blob>> {
		let headerXml: HttpHeaders = this.headers.set('Content-Type', 'application/xml')
		return this.httpClient.get(this.actionUrl + 'getXml/' + id, { responseType: 'blob', observe: 'response', headers: headerXml });
	}

	uploadFile(file: FileList, labelSent: string): Observable<DataTableData<DatasetListingModel>> {
		const params = new BaseHttpParams();
		params.interceptorContext = {
			excludedInterceptors: [InterceptorType.JSONContentType]
		};
		const formData = new FormData();
		formData.append('file', file[0], labelSent);
		return this.http.post(this.actionUrl + "upload", formData, { params: params });
	}

	externalAutocomplete(lookUpItem: RequestItem<DmpProfileExternalAutocompleteCriteria>): Observable<any> {
		return this.httpClient.post(this.actionUrl + 'search/autocomplete', lookUpItem);
	}
}
