import { HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { EndpointService } from '@app/shared/services/api/endpoint.service';
import { ApiFormatterService } from '@app/shared/services/api/formatter.service';
import { ApiService } from '@shared/services/api/api.service';
import { IStringValues } from '@typings/common/util';
import { IDestinationsResponse, IDaysResponse } from '@typings/responses';
import { Observable, of } from 'rxjs';
import { delay } from 'rxjs/operators';

export type IDestinationsRequestParams = {
    departure: string;
    arrival?: string;
    dateFrom: Date;
    dateTo?: Date;
    timeFrom?: string;
    timeTo?: string;
    connections?: number;
};

type IDestinationsHttpParams = IStringValues<IDestinationsRequestParams>;

@Injectable({
  providedIn: 'root'
})
export class FlightsMapApiService {

  constructor(private apiService: ApiService, 
    private apiFormatter: ApiFormatterService, 
    private endpointService: EndpointService) { }


  getDestinations(requestParams: IDestinationsRequestParams): Observable<IDestinationsResponse>{
    const url = this.endpointService.buildLocalizedURL('destinations', '1');

    const httpParams: IDestinationsHttpParams = {
      ...requestParams,
      dateFrom: this.apiFormatter.formatDateOnly(requestParams.dateFrom),
      dateTo: this.apiFormatter.formatDateOnly(requestParams.dateTo ?? this.addDays(requestParams.dateFrom, 1)),
      connections: String(requestParams.connections ?? 0),
    };

    let params = new HttpParams({
        fromObject: httpParams,
    });

    return this.apiService.cacheFirst$<IDestinationsResponse>(url, params);
  }

  public getFlightDaysByRoute(date: Date, src: string, dest: string, connections: boolean): Observable<IDaysResponse> {
    const formatDate = this.apiFormatter.formatDateOnly(date);

    let param = '';

    if(src && !dest)
    {
      param = `departure/${src}`
    }
    else if(src && dest)
    {
      param = connections ? `connections/${src}-${dest}-1` : `route/${src}-${dest}`;
    }
    else
    {
      return of<null>();
    }

    const url = this.endpointService.buildLocalizedURL(
        `days/${formatDate}/200/${param}/flights-map/`, //`days/${formatDate}/185/${param}/flights-map/`  расширено до 200, чтобы при нахождении на сайте нескольких дней актуальность календаря 
        'v1',                              // сохранялась по заранее запрошенным данным (не делать автообновление, возможно на будущую доработку по автообновлению)
    );
    console.log(url);
    const httpParams = new HttpParams({
    });

    return this.apiService.cacheFirst$<IDaysResponse>(url, httpParams);
  }

  private addDays(date: Date, days: number): Date {
    const newDate = new Date(date.getTime() + (1000 * 60 * 60 * 24 * days));

    return newDate;
  }
}
