import { Component, OnDestroy, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { FormBuilder, FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatOptionModule } from '@angular/material/core';
import { MatSelectModule } from '@angular/material/select';
import { Observable, Subscription } from 'rxjs';
import { map, startWith, take } from 'rxjs/operators';

import {
    AeronefByImat,
    CanopyModelBySize,
    DropZoneByOaci,
    Errors,
    Jump,
    JumpAddParams,
    JumpByModule,
    JumpFile,
    JumpFileType,
} from '@models';
import { AeronefsService, CanopiesService, DropZonesService, JumpsService } from '@services';

@Component({
    selector: 'app-jump-add-dialog',
    templateUrl: 'jump-add.dialog.html',
    imports: [
        AsyncPipe,
        FormsModule,
        ReactiveFormsModule,
        MatAutocompleteModule,
        MatButtonModule,
        MatCheckboxModule,
        MatDatepickerModule,
        MatDialogModule,
        MatFormFieldModule,
        MatIconModule,
        MatInputModule,
        MatSelectModule,
        MatOptionModule,
    ],
})
export class JumpAddDialogComponent implements OnDestroy {
    dialogRef = inject<MatDialogRef<JumpAddDialogComponent>>(MatDialogRef);
    private fb = inject(FormBuilder);
    private _aeronefsService = inject(AeronefsService);
    private _canopiesService = inject(CanopiesService);
    private _dropZonesService = inject(DropZonesService);
    private _jumpsService = inject(JumpsService);
    data = inject<{
        jump: Jump;
        lastJump: Jump;
    }>(MAT_DIALOG_DATA);

    private _formChanges: Array<Subscription> = [];
    private _subscriptions: Array<Subscription> = [];
    private _aeronefByImat: Subscription = new Subscription();
    private _canopyModelBySize: Subscription = new Subscription();
    private _dropZoneByOaci: Subscription = new Subscription();
    private _jumpByModule: Subscription = new Subscription();
    public errors!: Errors;
    public tagField = new FormControl<string>('', { nonNullable: true });
    public jumpForm: FormGroup;
    public jump: Jump;
    public lastJump: Jump;
    public nextJump: number;
    public params: JumpAddParams;
    public filename: string;
    public filepath: string;
    public useLast: {
        all: boolean;
        aeronef: boolean;
        altitude: boolean;
        discipline: boolean;
        divers: boolean;
        dropzone: boolean;
        groupe: boolean;
        programme: boolean;
        voile: boolean;
    } = {
        all: false,
        aeronef: false,
        altitude: false,
        discipline: false,
        divers: false,
        dropzone: false,
        groupe: false,
        programme: false,
        voile: false,
    };
    public inputOptions: {
        aeronefs: Array<AeronefByImat>;
        canopies: Array<CanopyModelBySize>;
        dropzones: Array<DropZoneByOaci>;
        categories: Array<JumpByModule>;
    };
    public filteredOptions: {
        aeronefs: Observable<Array<AeronefByImat>>;
        imats: Observable<Array<AeronefByImat>>;
        canopies: Observable<Array<CanopyModelBySize>>;
        tailles: Observable<Array<CanopyModelBySize>>;
        dropzones: Observable<Array<DropZoneByOaci>>;
        oaci: Observable<Array<DropZoneByOaci>>;
        categories: Observable<Array<JumpByModule>>;
        modules: Observable<Array<JumpByModule>>;
    };

    constructor() {
        const data = this.data;

        this.inputOptions = { aeronefs: [], canopies: [], dropzones: [], categories: [] };
        //this.filteredOptions.aeronefs = this._aeronefsService.getAllByImat();
        this.jump = data.jump;
        this.lastJump = data.lastJump;
        this.nextJump = this.lastJump.numero + 1;
        this.params = {
            numeros: this.nextJump.toString(),
            date: '',
            video: true,
        };
        this.jump.numero = this.nextJump;
        const controlsConfig = {
            date: ['', Validators.required],
            numero: [this.nextJump, Validators.required],
            lieu: ['', Validators.required],
            oaci: '',
            aeronef: ['', Validators.required],
            imat: '',
            hauteur: ['', Validators.required],
            deploiement: '',
            voile: '',
            taille: ['', Validators.required],
            categorie: '',
            module: '',
            participants: [1, Validators.required],
            sautants: [[]],
            programme: '',
            accessoires: '',
            zone: '',
            dossier: '',
            video: '',
        };
        this.jumpForm = this.fb.group(controlsConfig);
        this.filename = this._computeFilename();
        this.filepath = this._computeFilepath();
        this._subscriptions.push(
            this.jumpForm.controls['module'].valueChanges.subscribe(() => {
                this.filepath = this._computeFilepath();
            }),
            this.jumpForm.controls['numero'].valueChanges.subscribe(() => {
                this.filename = this._computeFilename();
            }),
        );
        /*
        this.filteredAeronefOptions = this.jumpForm.controls['aeronef'].valueChanges.pipe(
            startWith(''),
            map(value => {
                const aeronef = typeof value === 'string' ? value : '';
                return aeronef ? this._filterString(aeronef as string, this.aeronefOptions) : this.aeronefOptions.slice();
            }),
        );
        this.filteredImatOptions = this.jumpForm.controls['imat'].valueChanges.pipe(
            startWith(''),
            map(value => {
                const imat = typeof value === 'string' ? value : value?.imat;
                return imat ? this._filterImat(imat as string) : this.imatOptions.slice();
            }),
        );
        //this.filteredAeronefOptions = this._aeronefsService.getAllByImat();
        */
        this.filteredOptions = {
            aeronefs: this.jumpForm.controls['aeronef'].valueChanges.pipe(
                startWith(''),
                map((value) => {
                    const aeronef = typeof value === 'string' ? value : value?.aeronef;
                    return aeronef ? this._filterImat(aeronef as string) : this.inputOptions.aeronefs.slice();
                }),
            ),
            imats: this.jumpForm.controls['imat'].valueChanges.pipe(
                startWith(''),
                map((value) => {
                    const imat = typeof value === 'string' ? value : value?.imat;
                    return imat ? this._filterImat(imat as string) : this.inputOptions.aeronefs.slice();
                }),
            ),
            canopies: this.jumpForm.controls['voile'].valueChanges.pipe(
                startWith(''),
                map((value) => {
                    const voile = typeof value === 'string' ? value : value?.voile;
                    return voile ? this._filterTaille(voile as string) : this.inputOptions.canopies.slice();
                }),
            ),
            tailles: this.jumpForm.controls['taille'].valueChanges.pipe(
                startWith(''),
                map((value) => {
                    const taille = typeof value === 'string' ? value : value?.taille.toString();
                    return taille ? this._filterTaille(taille as string) : this.inputOptions.canopies.slice();
                }),
            ),
            dropzones: this.jumpForm.controls['lieu'].valueChanges.pipe(
                startWith(''),
                map((value) => {
                    const lieu = typeof value === 'string' ? value : value?.lieu;
                    return lieu ? this._filterOaci(lieu as string) : this.inputOptions.dropzones.slice();
                }),
            ),
            oaci: this.jumpForm.controls['oaci'].valueChanges.pipe(
                startWith(''),
                map((value) => {
                    const oaci = typeof value === 'string' ? value : value?.oaci;
                    return oaci ? this._filterOaci(oaci as string) : this.inputOptions.dropzones.slice();
                }),
            ),
            categories: this.jumpForm.controls['categorie'].valueChanges.pipe(
                startWith(''),
                map((value) => {
                    const category = typeof value === 'string' ? value : value?.categorie;
                    return category ? this._filterModule(category as string) : this.inputOptions.categories.slice();
                }),
            ),
            modules: this.jumpForm.controls['module'].valueChanges.pipe(
                startWith(''),
                map((value) => {
                    const module = typeof value === 'string' ? value : value?.module;
                    return module ? this._filterModule(module as string) : this.inputOptions.categories.slice();
                }),
            ),
        };
        this._loadAeronefByImat();
        this._loadCanopyModelBySize();
        this._loadDropZoneByOaci();
        this._loadJumpByModule();
    }

    ngOnDestroy() {
        this._subscriptions.forEach((sub: Subscription) => {
            sub.unsubscribe();
        });
        this._aeronefByImat.unsubscribe();
        this._canopyModelBySize.unsubscribe();
        this._dropZoneByOaci.unsubscribe();
        this._jumpByModule.unsubscribe();
    }

    public onDateChange(): void {
        this.filename = this._computeFilename();
    }

    private _computeFilename(numero?: string): string {
        let file: string = '';
        const timestamp: number = Date.parse(this.jumpForm.controls['date'].value);
        if (isNaN(timestamp) == false) {
            const date: Date = new Date(timestamp);
            file += `${(date.getFullYear() + '').padStart(2, '0')}-${(date.getMonth() + 1 + '').padStart(2, '0')}-${(date.getDate() + '').padStart(2, '0')}_`;
        }
        if (numero !== undefined) {
            numero = (numero + '').padStart(5, '0');
        } else {
            numero = (this.jumpForm.controls['numero'].value + '').padStart(5, '0');
        }
        file += `S${numero}.mp4`;
        this.jumpForm.controls['video'].setValue(file);

        return file;
    }

    private _computeFilepath(): string {
        let path: string = '/Volumes/Storage/Skydive/Videos/';
        if (this.jumpForm.controls['module'].value != '') {
            //path += `${this.jumpForm.controls['module'].value}/`;
            path +=
                typeof this.jumpForm.controls['module'].value === 'string'
                    ? `${this.jumpForm.controls['module'].value}/`
                    : `${this.jumpForm.controls['module'].value?.module}/`;
        }
        this.jumpForm.controls['dossier'].setValue(path);

        return path;
    }

    private _isLastForAllSections() {
        return (
            this.useLast.aeronef &&
            this.useLast.altitude &&
            this.useLast.discipline &&
            this.useLast.divers &&
            this.useLast.dropzone &&
            this.useLast.groupe &&
            this.useLast.programme &&
            this.useLast.voile
        );
    }

    private _filterImat(imat: string): Array<AeronefByImat> {
        const filterValue = imat.toLowerCase();
        return this.inputOptions.aeronefs.filter(
            (option) =>
                option.aeronef.toLowerCase().includes(filterValue) || option.imat.toLowerCase().includes(filterValue),
        );
    }

    private _filterModule(module: string): Array<JumpByModule> {
        const filterValue = module.toLowerCase();
        return this.inputOptions.categories.filter(
            (option) =>
                option.categorie.toLowerCase().includes(filterValue) ||
                option.module.toLowerCase().includes(filterValue),
        );
    }

    private _filterOaci(oaci: string): Array<DropZoneByOaci> {
        const filterValue = oaci.toLowerCase();
        return this.inputOptions.dropzones.filter(
            (option) =>
                option.lieu.toLowerCase().includes(filterValue) || option.oaci.toLowerCase().includes(filterValue),
        );
    }

    private _filterTaille(taille: string): Array<CanopyModelBySize> {
        const filterValue = taille.toLowerCase();
        return this.inputOptions.canopies.filter(
            (option) =>
                option.voile.toLowerCase().includes(filterValue) || option.taille.toString().includes(filterValue),
        );
    }

    private _loadAeronefByImat(): void {
        const aeronefs$ = this._aeronefsService.getAllByImat();
        const subscription: Subscription = aeronefs$.subscribe((aggregate: Array<AeronefByImat>) => {
            /*
            this.inputOptions.imats = aggregate.map((row: AeronefByImat) => {
                if (this.inputOptions.aeronefs.indexOf(row.aeronef) === -1) {
                    this.inputOptions.aeronefs.push(row.aeronef);
                }
                return row;
            });
            */
            this.inputOptions.aeronefs = aggregate;
        });
        this._subscriptions.push(subscription);
    }

    private _loadCanopyModelBySize(): void {
        const canopies$ = this._canopiesService.getAllBySizeByModel();
        const subscription: Subscription = canopies$.subscribe((aggregate: Array<CanopyModelBySize>) => {
            /*
            this.inputOptions.tailles = aggregate.map((row: CanopyModelBySize) => {
                if (this.inputOptions.canopies.indexOf(row.voile) === -1) {
                    this.inputOptions.canopies.push(row.voile);
                }
                return row;
            });
            */
            this.inputOptions.canopies = aggregate;
        });
        this._subscriptions.push(subscription);
    }

    private _loadDropZoneByOaci(): void {
        const dropzones$ = this._dropZonesService.getAllByOaci();
        const subscription: Subscription = dropzones$.subscribe((aggregate: Array<DropZoneByOaci>) => {
            /*
            this.inputOptions.oaci = aggregate.map((row: DropZoneByOaci) => {
                if (this.inputOptions.dropzones.indexOf(row.lieu) === -1) {
                    this.inputOptions.dropzones.push(row.lieu);
                }
                return row;
            });
            */
            this.inputOptions.dropzones = aggregate;
        });
        this._subscriptions.push(subscription);
    }

    private _loadJumpByModule(): void {
        const jumps$ = this._jumpsService.getAllByModule();
        const subscription: Subscription = jumps$.subscribe((aggregate: Array<JumpByModule>) => {
            this.inputOptions.categories = aggregate;
        });
        this._subscriptions.push(subscription);
    }

    private _setAllLast(checked: boolean) {
        this.useLast.all = checked;
        this.useLast.aeronef = checked;
        this.useLast.altitude = checked;
        this.useLast.discipline = checked;
        this.useLast.divers = checked;
        this.useLast.dropzone = checked;
        this.useLast.groupe = checked;
        this.useLast.programme = checked;
        this.useLast.voile = checked;
    }

    addSautant(): void {
        this.useLast.groupe = false;
        this.useLast.all = this._isLastForAllSections();
        const tag = this.tagField.value;
        if (tag != null && tag.trim() !== '') {
            if (tag.includes(',') === true) {
                const tags = tag.split(',');
                tags.forEach((sautant) => {
                    if (this.jump.sautants.indexOf(sautant.trim()) < 0) {
                        this.jump.sautants.push(sautant.trim());
                    }
                });
            } else if (this.jump.sautants.indexOf(tag) < 0) {
                this.jump.sautants.push(tag);
            }
        }
        this.tagField.reset('');
        const participants = this.jump.sautants.length + 1;
        this.jumpForm.controls['participants'].setValue(participants);
    }

    closeDialog(): void {
        this._setAllLast(false);
        //this.jump = <Jump>{};
        //this.jump.numero = this.nextJump;
        this.dialogRef.close();
    }

    displayAeronefFn(aeronef: AeronefByImat): string {
        let res = '';
        if (aeronef) {
            if (typeof aeronef === 'string') {
                res = aeronef;
            } else {
                res = aeronef.aeronef ? aeronef.aeronef : '';
            }
        }
        return res;
    }

    displayImatFn(aeronef: AeronefByImat): string {
        let res = '';
        if (aeronef) {
            if (typeof aeronef === 'string') {
                res = aeronef;
            } else {
                res = aeronef.imat ? aeronef.imat : '';
            }
        }
        return res;
    }

    displayLieuFn(dropzone: DropZoneByOaci): string {
        //return dropzone && dropzone.oaci ? `${dropzone.lieu} - ${dropzone.oaci}` : '';
        let res = '';
        if (dropzone) {
            if (typeof dropzone === 'string') {
                res = dropzone;
            } else {
                res = dropzone.lieu ? dropzone.lieu : '';
            }
        }
        //return dropzone && dropzone.lieu ? dropzone.lieu : '';
        return res;
    }

    displayOaciFn(dropzone: DropZoneByOaci): string {
        //return dropzone && dropzone.oaci ? `${dropzone.lieu} - ${dropzone.oaci}` : '';
        let res = '';
        if (dropzone) {
            if (typeof dropzone === 'string') {
                res = dropzone;
            } else {
                res = dropzone.oaci ? dropzone.oaci : '';
            }
        }
        //return dropzone && dropzone.oaci ? dropzone.oaci : '';
        return res;
    }

    displayTailleFn(canopy: CanopyModelBySize): string {
        let res = '';
        if (canopy) {
            if (typeof canopy === 'string') {
                res = canopy;
            } else {
                res = canopy.taille ? canopy.taille.toString() : '';
            }
        }
        return res;
    }

    displayVoileFn(canopy: CanopyModelBySize): string {
        let res = '';
        if (canopy) {
            if (typeof canopy === 'string') {
                res = canopy;
            } else {
                res = canopy.voile ? canopy.voile : '';
            }
        }
        return res;
    }

    displayCategorieFn(jump: JumpByModule): string {
        let res = '';
        if (jump) {
            if (typeof jump === 'string') {
                res = jump;
            } else {
                res = jump.categorie ? jump.categorie : '';
            }
        }
        return res;
    }

    displayModuleFn(jump: JumpByModule): string {
        let res = '';
        if (jump) {
            if (typeof jump === 'string') {
                res = jump;
            } else {
                res = jump.module ? jump.module : '';
            }
        }
        return res;
    }

    getErrorMessage(name: string): string {
        if (this.jumpForm.controls[name].errors !== null) {
            return 'Ce champ est requis.';
        }
        return '';
    }

    onSelAeronef(aeronef: AeronefByImat) {
        if (aeronef && aeronef.aeronef) {
            //this.jumpForm.controls['imat'].setValue(aeronef.imat);
            this.jumpForm.controls['imat'].setValue(aeronef);
        }
    }

    onSelImat(aeronef: AeronefByImat) {
        if (aeronef && aeronef.imat) {
            //this.jumpForm.controls['aeronef'].setValue(aeronef.aeronef);
            this.jumpForm.controls['aeronef'].setValue(aeronef);
        }
    }

    onSelLieu(dropzone: DropZoneByOaci) {
        if (dropzone && dropzone.oaci) {
            //this.jumpForm.controls['oaci'].setValue(dropzone.oaci);
            this.jumpForm.controls['oaci'].setValue(dropzone);
        }
    }

    onSelOaci(dropzone: DropZoneByOaci) {
        if (dropzone && dropzone.lieu) {
            //this.jumpForm.controls['lieu'].setValue(dropzone.lieu);
            this.jumpForm.controls['lieu'].setValue(dropzone);
        }
    }

    onSelTaille(canopy: CanopyModelBySize) {
        if (canopy && canopy.voile) {
            //this.jumpForm.controls['voile'].setValue(canopy.voile);
            this.jumpForm.controls['voile'].setValue(canopy);
        }
    }

    onSelVoile(canopy: CanopyModelBySize) {
        if (canopy && canopy.taille) {
            //this.jumpForm.controls['taille'].setValue(canopy.taille.toString());
            this.jumpForm.controls['taille'].setValue(canopy);
        }
    }

    onSelCategorie(jump: JumpByModule) {
        if (jump && jump.categorie) {
            this.jumpForm.controls['module'].setValue(jump);
        }
    }

    onSelModule(jump: JumpByModule) {
        if (jump && jump.module) {
            this.jumpForm.controls['categorie'].setValue(jump);
        }
    }

    removeSautant(index: string): void {
        this.useLast.groupe = false;
        this.useLast.all = this._isLastForAllSections();
        this.jump.sautants = this.jump.sautants.filter((sautant) => sautant !== index);
        const participants = this.jump.sautants.length + 1;
        this.jumpForm.controls['participants'].setValue(participants);
    }

    setLastJump(checked: boolean) {
        if (checked) {
            this._setAllLast(true);
            this.jumpForm.controls['lieu'].setValue(this.lastJump.lieu);
            this.jumpForm.controls['oaci'].setValue(this.lastJump.oaci);
            this.jumpForm.controls['aeronef'].setValue(this.lastJump.aeronef);
            this.jumpForm.controls['imat'].setValue(this.lastJump.imat);
            this.jumpForm.controls['hauteur'].setValue(this.lastJump.hauteur);
            this.jumpForm.controls['deploiement'].setValue(this.lastJump.deploiement);
            this.jumpForm.controls['voile'].setValue(this.lastJump.voile);
            this.jumpForm.controls['taille'].setValue(this.lastJump.taille?.toString());
            this.jumpForm.controls['categorie'].setValue(this.lastJump.categorie);
            this.jumpForm.controls['module'].setValue(this.lastJump.module);
            this.jumpForm.controls['participants'].setValue(this.lastJump.participants);
            //this.jumpForm.controls['sautants'].setValue(this.lastJump.sautants);
            this.jumpForm.controls['programme'].setValue(this.lastJump.programme);
            this.jumpForm.controls['accessoires'].setValue(this.lastJump.accessoires);
            this.jumpForm.controls['zone'].setValue(this.lastJump.zone);
            this.jump.sautants = this.lastJump.sautants;
            /*
            Object.assign(
                this.jump,
                {
                    date: this.lastJump.date,
                    numero: this.lastJump.numero,
                    lieu: this.lastJump.lieu,
                    oaci: this.lastJump.oaci,
                    aeronef: this.lastJump.aeronef,
                    imat: this.lastJump.imat,
                    hauteur: this.lastJump.hauteur,
                    deploiement: this.lastJump.deploiement,
                    voile: this.lastJump.voile,
                    taille: this.lastJump.taille,
                    categorie: this.lastJump.categorie,
                    module: this.lastJump.module,
                    participants: this.lastJump.participants,
                    sautants: this.lastJump.sautants,
                    programme: this.lastJump.programme,
                    accessoires: this.lastJump.accessoires,
                    zone: this.lastJump.zone,
                }
            );
            */
            this.jump.date = '';
        } else {
            this._setAllLast(false);
            this.jumpForm.controls['lieu'].setValue('');
            this.jumpForm.controls['oaci'].setValue('');
            this.jumpForm.controls['aeronef'].setValue('');
            this.jumpForm.controls['imat'].setValue('');
            this.jumpForm.controls['hauteur'].setValue('');
            this.jumpForm.controls['deploiement'].setValue('');
            this.jumpForm.controls['voile'].setValue('');
            this.jumpForm.controls['taille'].setValue('');
            this.jumpForm.controls['categorie'].setValue('');
            this.jumpForm.controls['module'].setValue('');
            this.jumpForm.controls['participants'].setValue(1);
            //this.jumpForm.controls['sautants'].setValue('');
            this.jumpForm.controls['programme'].setValue('');
            this.jumpForm.controls['accessoires'].setValue('');
            this.jumpForm.controls['zone'].setValue('');
            this.jump.sautants = [];
        }
        this.jump.numero = this.nextJump;
    }

    setLastAeronef(checked: boolean = false) {
        if (checked) {
            this.useLast.aeronef = true;
            this.jumpForm.controls['aeronef'].setValue(this.lastJump.aeronef);
            this.jumpForm.controls['imat'].setValue(this.lastJump.imat);
        } else {
            this.useLast.aeronef = false;
            this.jumpForm.controls['aeronef'].setValue('');
            this.jumpForm.controls['imat'].setValue('');
        }
        this.useLast.all = this._isLastForAllSections();
    }

    setLastAltitude(checked: boolean = false) {
        if (checked) {
            this.useLast.altitude = true;
            this.jumpForm.controls['hauteur'].setValue(this.lastJump.hauteur);
            this.jumpForm.controls['deploiement'].setValue(this.lastJump.deploiement);
        } else {
            this.useLast.altitude = false;
            this.jumpForm.controls['hauteur'].setValue('');
            this.jumpForm.controls['deploiement'].setValue('');
        }
        this.useLast.all = this._isLastForAllSections();
    }

    setLastDiscipline(checked: boolean = false) {
        if (checked) {
            this.useLast.discipline = true;
            this.jumpForm.controls['categorie'].setValue(this.lastJump.categorie);
            this.jumpForm.controls['module'].setValue(this.lastJump.module);
        } else {
            this.useLast.discipline = false;
            this.jumpForm.controls['categorie'].setValue('');
            this.jumpForm.controls['module'].setValue('');
        }
        this.useLast.all = this._isLastForAllSections();
    }

    setLastDivers(checked: boolean = false) {
        if (checked) {
            this.useLast.divers = true;
            this.jumpForm.controls['accessoires'].setValue(this.lastJump.accessoires);
            this.jumpForm.controls['zone'].setValue(this.lastJump.zone);
        } else {
            this.useLast.divers = false;
            this.jumpForm.controls['accessoires'].setValue('');
            this.jumpForm.controls['zone'].setValue('');
        }
        this.useLast.all = this._isLastForAllSections();
    }

    setLastDropzone(checked: boolean = false) {
        if (checked) {
            this.useLast.dropzone = true;
            this.jumpForm.controls['lieu'].setValue(this.lastJump.lieu);
            this.jumpForm.controls['oaci'].setValue(this.lastJump.oaci);
        } else {
            this.useLast.dropzone = false;
            this.jumpForm.controls['lieu'].setValue('');
            this.jumpForm.controls['oaci'].setValue('');
        }
        this.useLast.all = this._isLastForAllSections();
    }

    setLastGroupe(checked: boolean = false) {
        if (checked) {
            this.useLast.groupe = true;
            this.jumpForm.controls['participants'].setValue(this.lastJump.participants);
            //this.jumpForm.controls['sautants'].setValue(this.lastJump.sautants);
            this.jump.sautants = this.lastJump.sautants;
        } else {
            this.useLast.groupe = false;
            this.jumpForm.controls['participants'].setValue(1);
            //this.jumpForm.controls['sautants'].setValue('');
            this.jump.sautants = [];
        }
        this.useLast.all = this._isLastForAllSections();
    }

    setLastProgramme(checked: boolean = false) {
        if (checked) {
            this.useLast.programme = true;
            this.jumpForm.controls['programme'].setValue(this.lastJump.participants);
        } else {
            this.useLast.programme = false;
            this.jumpForm.controls['programme'].setValue('');
        }
        this.useLast.all = this._isLastForAllSections();
    }

    setLastVoile(checked: boolean = false) {
        if (checked) {
            this.useLast.voile = true;
            this.jumpForm.controls['voile'].setValue(this.lastJump.voile);
            this.jumpForm.controls['taille'].setValue(this.lastJump.taille?.toString());
        } else {
            this.useLast.voile = false;
            this.jumpForm.controls['voile'].setValue('');
            this.jumpForm.controls['taille'].setValue('');
        }
        this.useLast.all = this._isLastForAllSections();
    }

    submitForm(): void {
        /*
         * Création d'un tableau de saut contenant de 1 à n saut en fonction
         * de la valeur du champ numero du formulaire jumpForm
         */
        const jumps: Array<Jump> = [];
        const jump: Jump = {} as Jump;
        const numeros: Array<number> = [];
        let date: Date;
        /* Controle de la validité du champ date et conversion au format ISO */
        const timestamp: number = Date.parse(this.jumpForm.controls['date'].value);
        if (isNaN(timestamp) == false) {
            date = new Date(timestamp);
        } else {
            date = new Date();
        }
        let value = this.jumpForm.controls['numero'].value;
        if (typeof value !== 'string') {
            value = value.toString();
        }

        if (isNaN(+value) || value.split('+').length == 2) {
            /*
             * 'numero' n'est pas un entier , il s'agit donc d'une plage, d'une quantité ou de plusieurs valeur
             * decomposer la valeur 'numero' et ajouter chaque sauts au tableau retourné par la fenêtre dialog
             */
            let jumpNum: number = this.lastJump.numero;
            const elements: string[] = this.jumpForm.controls['numero'].value.split(';');
            elements.forEach((element: string) => {
                if (element == '') {
                    jumpNum++;
                    element = jumpNum.toString();
                }
                const values: string[] = element.split('-');
                if (values.length == 2) {
                    const start: number = parseInt(values[0]);
                    const stop: number = parseInt(values[1]);
                    const diff: number = stop - start;
                    /* Ajout de saut par plage */
                    for (let index = 0; index <= diff; index++) {
                        jumpNum = start + index;
                        numeros.push(jumpNum);
                    }
                } else {
                    const quantity: string[] = values[0].split('+');
                    if (quantity.length == 2) {
                        /* Ajout de sauts par quantité */
                        //const start: number = jumpNum;
                        for (let index = 1; index <= parseInt(quantity[1]); index++) {
                            jumpNum++;
                            numeros.push(jumpNum);
                        }
                    } else {
                        /* Ajout de sauts par numero */
                        jumpNum = parseInt(quantity[0]);
                        numeros.push(jumpNum);
                    }
                }
            });
        } else {
            /* 'numero' est un entier */
            numeros.push(this.jumpForm.controls['numero'].value);
        }

        /* Valeurs communes aux 1 à n saut(s) à ajouter */
        jump.date = date.toISOString();
        jump.lieu =
            typeof this.jumpForm.controls['lieu'].value === 'string'
                ? this.jumpForm.controls['lieu'].value
                : this.jumpForm.controls['lieu'].value.lieu;
        jump.oaci =
            typeof this.jumpForm.controls['oaci'].value === 'string'
                ? this.jumpForm.controls['oaci'].value
                : this.jumpForm.controls['oaci'].value.oaci;
        jump.aeronef =
            typeof this.jumpForm.controls['aeronef'].value === 'string'
                ? this.jumpForm.controls['aeronef'].value
                : this.jumpForm.controls['aeronef'].value.aeronef;
        jump.imat =
            typeof this.jumpForm.controls['imat'].value === 'string'
                ? this.jumpForm.controls['imat'].value
                : this.jumpForm.controls['imat'].value.imat;
        jump.voile =
            typeof this.jumpForm.controls['voile'].value === 'string'
                ? this.jumpForm.controls['voile'].value
                : this.jumpForm.controls['voile'].value.voile;
        jump.taille =
            typeof this.jumpForm.controls['taille'].value === 'string'
                ? this.jumpForm.controls['taille'].value
                : this.jumpForm.controls['taille'].value.taille;
        jump.categorie =
            typeof this.jumpForm.controls['categorie'].value === 'string'
                ? this.jumpForm.controls['categorie'].value
                : this.jumpForm.controls['categorie'].value.categorie;
        jump.module =
            typeof this.jumpForm.controls['module'].value === 'string'
                ? this.jumpForm.controls['module'].value
                : this.jumpForm.controls['module'].value.module;
        jump.hauteur = this.jumpForm.controls['hauteur'].value;
        jump.deploiement = this.jumpForm.controls['deploiement'].value;
        jump.participants = this.jumpForm.controls['participants'].value;
        jump.sautants = this.jump.sautants;
        //jump.sautants = this.jumpForm.controls['sautants'].value;
        jump.programme = this.jumpForm.controls['programme'].value;
        jump.accessoires = this.jumpForm.controls['accessoires'].value;
        jump.zone = this.jumpForm.controls['zone'].value;
        //jump.dossier = this.jumpForm.controls['dossier'].value;
        //jump.video = this.jumpForm.controls['video'].value;

        /* Ajout du saut au tableau à retourner */
        numeros.forEach((numero: number) => {
            const item: Jump = {} as Jump;
            Object.assign(item, jump);
            item.numero = numero;
            if (this.jumpForm.controls['dossier'].value !== '' && this.jumpForm.controls['video'].value !== '') {
                item.dossier = this._computeFilepath();
                item.video = this._computeFilename(numero.toString());
                const file: JumpFile = {
                    name: item.video,
                    path: item.dossier,
                    type: JumpFileType.VIDEO,
                } as JumpFile;
                this._subscriptions.push(
                    this._jumpsService
                        .saveFile(item.slug, file)
                        .pipe(take(1))
                        .subscribe({
                            next: (file) => {
                                item.files.push(file);
                                console.log(`Le fichier ${file.name} a été ajouté au saut n°${item.numero} !`, 'OK');
                            },
                            error: (err) => {
                                this.errors = err;
                            },
                        }),
                );
            }
            jumps.push(item);
            //console.log(item);
        });
        //console.log(jumps);
        /* Reset all 'last jump values' booleans */
        this._setAllLast(false);
        /* close the dialog with result */
        this.dialogRef.close(jumps);

        /*
        // Reset all 'last jump values' booleans
        this._setAllLast(false);
        // update the model
        this.updateJump(this.jumpForm.value);
        // close the dialog with result
        this.dialogRef.close(this.jump);
        */
    }

    updateJump(values: NonNullable<unknown>): void {
        Object.assign(this.jump, values);
    }
}
