import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { environment } from '../../../../environments/environment';
import { BaseHttpParams } from '../../../../common/http/base-http-params';
import { InterceptorType } from '../../../../common/http/interceptors/interceptor-type';
import { DynamicFieldGrantCriteria } from '../../../models/dynamic-field-grant/DynamicFieldGrantCriteria';
import { DataTableData } from '../../model/data-table/data-table-data';
import { DataTableRequest } from '../../model/data-table/data-table-request';
import { DatasetListingModel } from '../../model/dataset/dataset-listing';
import { DatasetProfileModel } from '../../model/dataset/dataset-profile';
import { DatasetsToBeFinalized } from '../../model/dataset/datasets-toBeFinalized';
import { DmpModel } from '../../model/dmp/dmp';
import { DmpListingModel } from '../../model/dmp/dmp-listing';
import { DmpOverviewModel } from '../../model/dmp/dmp-overview';
import { DatasetProfileCriteria } from '../../query/dataset-profile/dataset-profile-criteria';
import { DmpCriteria } from '../../query/dmp/dmp-criteria';
import { ExploreDmpCriteriaModel } from '../../query/explore-dmp/explore-dmp-criteria';
import { RequestItem } from '../../query/request-item';
import { BaseHttpService } from '../http/base-http.service';
import { ConfigurationService } from '../configuration/configuration.service';
import { UserInfoListingModel } from '@app/core/model/user/user-info-listing';
import { VersionListingModel } from '@app/core/model/version/version-listing.model';

@Injectable()
export class DmpService {

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

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

	}

	getPaged(dataTableRequest: DataTableRequest<DmpCriteria>, fieldsGroup?: string): Observable<DataTableData<DmpListingModel>> {
		if (fieldsGroup) {
			return this.http.post<DataTableData<DmpListingModel>>(this.actionUrl + 'paged?fieldsGroup=' + fieldsGroup, dataTableRequest, { headers: this.headers });
		}
		else {
			return this.http.post<DataTableData<DmpListingModel>>(this.actionUrl + 'paged?fieldsGroup=' + fieldsGroup, dataTableRequest, { headers: this.headers });
		}
	}

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

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

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

	getOverviewSingle(id: string): Observable<DmpOverviewModel> {
		return this.http.get<DmpOverviewModel>(this.actionUrl + 'overview/' + id, { headers: this.headers });
	}

	getOverviewSinglePublic(id: string): Observable<DmpOverviewModel> {
		return this.http.get<DmpOverviewModel>(this.actionUrl + 'publicOverview/' + id, { headers: this.headers })
	}

	getAllVersions(id: string, isPublic: boolean): Observable<VersionListingModel[]> {
		return this.http.get<VersionListingModel[]>(this.actionUrl + 'versions/' + id + '?public=' + isPublic, { headers: this.headers })
	}

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

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

	createDmpWithDatasets(dataManagementPlanModel: DmpModel): Observable<String> {
		return this.http.post<String>(this.actionUrl + 'full', dataManagementPlanModel, { headers: this.headers });
	}

	inactivate(id: String): Observable<DmpModel> {
		return this.http.delete<DmpModel>(this.actionUrl + 'inactivate/' + id, { headers: this.headers });
	}

	searchDMPProfiles(dataSetProfileRequest: RequestItem<DatasetProfileCriteria>): Observable<DatasetProfileModel[]> {
		return this.http.post<DatasetProfileModel[]>(this.actionUrl + 'datasetprofiles/get', dataSetProfileRequest, { headers: this.headers });
	}

	newVersion(dataManagementPlanModel: DmpModel, id: String): Observable<String> {
		return this.http.post<String>(this.actionUrl + 'new/' + id, dataManagementPlanModel, { headers: this.headers });
	}

	clone(dataManagementPlanModel: DmpModel, id: String): Observable<String> {
		return this.http.post<String>(this.actionUrl + 'clone/' + id, dataManagementPlanModel, { headers: this.headers });
	}

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

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

	finalize(datasetsToBeFinalized: DatasetsToBeFinalized, id: String): Observable<DmpModel> {
		return this.http.post<DmpModel>(this.actionUrl + 'finalize/' + id, datasetsToBeFinalized, { headers: this.headers });
	}

	unfinalize(id: String): Observable<DmpModel> {
		return this.http.post<DmpModel>(this.actionUrl + 'unfinalize/' + id, { headers: this.headers });
	}

	updateUsers(id: string, users: UserInfoListingModel[]): Observable<DmpModel> {
		return this.http.post<DmpModel>(`${this.actionUrl}updateusers/${id}`, users, { headers: this.headers });
	}

	getDoi(id: string): Observable<string> {
		return this.http.post<string>(this.actionUrl + 'createZenodoDoi/' + id, { headers: this.headers });
	}

	getDynamicField(requestItem: RequestItem<DynamicFieldGrantCriteria>): any {
		return this.http.post<any>(this.actionUrl + 'dynamic', requestItem, { 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 + id, { responseType: 'blob', observe: 'response', headers: headerXml }); //+ "/getXml/"
	}

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

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

	public downloadJson(id: string): Observable<HttpResponse<Blob>> {
		return this.httpClient.get(this.actionUrl + 'rda/' + id, { responseType: 'blob', observe: 'response' });
	}

	public uploadXml(fileList: FileList, dmpTitle: string, dmpProfiles: any[]): Observable<any> {
		const formData: FormData = new FormData();
		if (fileList instanceof FileList) {
			for (let i = 0; i < fileList.length; i++) {
				formData.append('file', fileList[i], dmpTitle);
			}
		} else if (Array.isArray(fileList)) {
			formData.append('file', fileList[0], dmpTitle);
		} else {
			formData.append('file', fileList, dmpTitle);
		}
		for (let j = 0; j < dmpProfiles.length; j++) {
			formData.append('profiles', dmpProfiles[j].id);
		}
		const params = new BaseHttpParams();
		params.interceptorContext = {
			excludedInterceptors: [InterceptorType.JSONContentType]
		};
		return this.http.post(this.actionUrl + 'upload', formData, { params: params });
	}

	getPublicPaged(dataTableRequest: DataTableRequest<ExploreDmpCriteriaModel>, fieldsGroup?: string): Observable<DataTableData<DmpListingModel>> {
		return this.http.post<DataTableData<DmpListingModel>>(this.actionUrl + 'public/paged?fieldsGroup=' + fieldsGroup, dataTableRequest, { headers: this.headers });
	}

	getDatasetProfilesUsedPaged(dataTableRequest: DataTableRequest<DatasetProfileCriteria>) {
		return this.http.post<DataTableData<DatasetListingModel>>(this.actionUrl + 'datasetProfilesUsedByDmps/paged', dataTableRequest);
	}

	generateIndex() {
		return this.http.post(this.actionUrl + 'index', {});
	}

	clearIndex() {
		return this.http.delete(this.actionUrl + 'index');
	}
}
