import {RequestItem} from "@app/core/query/request-item";
import {ResearcherCriteria} from "@app/core/query/researcher/researcher-criteria";
import {Observable} from "rxjs";
import {ExternalSourceItemModel} from "@app/core/model/external-sources/external-source-item";
import {Injectable} from "@angular/core";
import {HttpClient, HttpHeaders, HttpResponse} from "@angular/common/http";
import {BaseHttpService} from "@app/core/services/http/base-http.service";
import {ConfigurationService} from "@app/core/services/configuration/configuration.service";
import {BaseHttpParams} from "@common/http/base-http-params";
import {InterceptorType} from "@common/http/interceptors/interceptor-type";
import {tap} from "rxjs/operators";

@Injectable()
export class FileService {

	private actionUrl: string;
	private headers: HttpHeaders;

	constructor(private http: BaseHttpService, private httpClient: HttpClient, private configurationService: ConfigurationService) {

		this.actionUrl = configurationService.server + 'file/';

		this.headers = new HttpHeaders();
		this.headers = this.headers.set('Content-Type', 'application/json');
		this.headers = this.headers.set('Accept', 'application/json');
	}

	public upload(fileList: File, datasetProfileId: string, fieldId: string): Observable<any> {
		const formData: FormData = new FormData();
		// if (fileList instanceof FileList) {
		// 	for (let i = 0; i < fileList.length; i++) {
		// 		formData.append('file', fileList[i], "test-konstantina");
		// 	}
		// } else if (Array.isArray(fileList)) {
		// 	formData.append('files', fileList);
		// } else {
			formData.append('file', fileList);
			formData.append('datasetProfileId', datasetProfileId);
			formData.append('fieldId', fieldId);
		// }
		// formData.append("fileType", fileList.)
		console.log(fileList.type, fileList.name, fileList.size);
		const params = new BaseHttpParams();
		params.interceptorContext = {
			excludedInterceptors: [InterceptorType.JSONContentType]
		};
		return this.http.post(this.actionUrl + 'upload', formData
			, { params: params }
		);
	}

	public deleteFromTempFolder(uuid: string) {
		const params = new BaseHttpParams();
		params.interceptorContext = {
			excludedInterceptors: [InterceptorType.JSONContentType]
		};
		return this.http.post(this.actionUrl + 'delete-temp', uuid
			, { params: params }
		);
	}

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