import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

import { JumpResp, JumpReq } from '../models/jump';

import { DateService } from './date.service';
import { BaseService } from './base.service';


@Injectable()
export class JumpService extends BaseService {
  constructor(private http: HttpClient, private dateService: DateService) {
    super();
  }

  public getListOfJumps(): Observable<Array<JumpResp>> {
    return this.http.get<Array<JumpResp>>(`${this.apiUrl}/Jump`, {
      headers: this.headers
    })
      .pipe(
        map(response => {
          const details = response.map(data => new JumpResp(data));
          return details;
        })
      );
  }

  public AddListOfJump(
    selectedJumpType: number,
    selectedAircraft: number,
    selectedDz: number,
    selectedRig: number,
    withCutaway: boolean,
    beginDate: Date,
    endDate: Date,
    defaultExitAltitude: number,
    defaultDeployAltitude: number,
    countOfJumps: number
  ) {
    const diffInDays =
      this.dateService.DiffBetweenDates(beginDate, endDate) + 1;
    const countOfJumpsPerDay = Math.trunc(countOfJumps / diffInDays);

    for (let i = 1; beginDate.getTime() < endDate.getTime(); i++) {
      this.AddJumps(
        selectedJumpType,
        selectedAircraft,
        selectedDz,
        selectedRig,
        withCutaway,
        beginDate,
        defaultExitAltitude,
        defaultDeployAltitude,
        countOfJumpsPerDay
      );

      beginDate = this.dateService.AddDays(beginDate, 1);
    }

    const restfJumps = countOfJumps - countOfJumpsPerDay * (diffInDays - 1);
    this.AddJumps(
      selectedJumpType,
      selectedAircraft,
      selectedDz,
      selectedRig,
      withCutaway,
      beginDate,
      defaultExitAltitude,
      defaultDeployAltitude,
      restfJumps
    );
  }

  private AddJumps(
    selectedJumpType: number,
    selectedAircraft: number,
    selectedDz: number,
    selectedRig: number,
    withCutaway: boolean,
    jumpDate: Date,
    defaultExitAltitude: number,
    defaultDeployAltitude: number,
    countOfJumps: number
  ) {
    for (let i = 0; i < countOfJumps; i++) {
      const bodyNewjump: JumpReq = {
        jumpTypeId: selectedJumpType,
        aircraftId: selectedAircraft,
        dropZoneId: selectedDz,
        withCutaway: withCutaway,
        exitAltitude: defaultExitAltitude,
        deployAltitude: defaultDeployAltitude,
        gearId: selectedRig,
        notes: '',
        id: 0,
        jumpDate: jumpDate
      };

      this.http
        .post(`${this.apiUrl}/Jump`, bodyNewjump, {
          headers: this.headers
        })
        .subscribe(data => console.log(data));
    }
  }
}
