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

import { Jump } from 'src/app/core/models';
import { environment } from 'src/environments/environment';

export interface JumpDoc {
    _id?: string;
    _rev?: string;
    type: string;
    date: string;
    numero: number,
    lieu?: string;
    oaci?: string;
    aeronef?: string;
    imat?: string;
    hauteur?: number,
    voile?: string;
    taille?: number,
    categorie?: string;
    module?: string;
    participants?: number,
    programme?: string;
    accessoires?: string;
    zone?: string;
    dossier?: string;
    video?: string;
}

export interface JumpViewResults {
    rows: Array<Jump>;
    total_rows: number;
}

@Injectable({ providedIn: 'root' })
export class BackendService {
    private _couchdbUrl = environment.couchdbUrl;
    private _couchdbDatabase = environment.couchdbDatabase;
    private _couchdbDesign = environment.couchdbDesign;
    private _couchdbCredential = environment.couchdbCredential;
    //private _couchdbUrl = "http://couchdb.unespace.com/material_grow/_design/netgrowing_app/_view/allDevices";

    httpOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json',
            'Authorization': 'Basic ' + this._couchdbCredential
        })
    }

    constructor(private _http: HttpClient) { }

    writeDoc(doc: Object): Promise<Object | undefined> {
        const url = this._couchdbUrl + '/' + this._couchdbDatabase;
        return this._http.post<Object>(url, doc, this.httpOptions).toPromise();
    }

    updateDoc(doc: JumpDoc): Promise<Object | undefined> {
        const url = `${this._couchdbUrl}/${this._couchdbDatabase}/${doc._id}`;
        return this._http.put<Object>(url, doc, this.httpOptions).toPromise();
    }

    deleteDoc(id: string, rev: string): Promise<Object | undefined> {
        //const url = this._couchdbUrl + '/' + this._couchdbDatabase + '/' + id + '?rev=' + rev;
        const url = `${this._couchdbUrl}/${this._couchdbDatabase}/${id}?rev=${rev}`;
        return this._http.delete(url, this.httpOptions).toPromise();
    }

    /* get all docs from couchDB view 'allJumps' */
    getJumps(): Observable<JumpViewResults> {
        //const url = this._couchdbUrl + '/' + this._couchdbDatabase + '/_design/' + this._couchdbDesign + '/_view/allJumps/';
        //return this._http.get(url, this.httpOptions);
        const payload = {
            "include_docs": false,
            "reduce": false,
            "descending": false
        }
        const url = `${this._couchdbUrl}/${this._couchdbDatabase}/_design/${this._couchdbDesign}/_view/allJumps/`;
        return this._http.post<JumpViewResults>(url, payload, this.httpOptions);
    }

    /* get all docs from couchDB view 'allJumpsByDate' */
    getJumpsByDate(level: number): Observable<Object> {
        const payload = {
            "reduce": true,
            "group": true,
            "group_level": level
        }
        const url = `${this._couchdbUrl}/${this._couchdbDatabase}/_design/${this._couchdbDesign}/_view/allJumpsByDate/`;
        return this._http.post(url, payload, this.httpOptions);
    }

    /* get all docs from couchDB view 'filterAeronef' */
    getAeronefs(): Observable<Object> {
        const payload = {
            "reduce": true,
            "group": true
        }
        const url = `${this._couchdbUrl}/${this._couchdbDatabase}/_design/${this._couchdbDesign}/_view/filterAeronef/`;
        return this._http.post(url, payload, this.httpOptions);
    }

    /* get all docs from couchDB view 'filterAeronefByDate' */
    getAeronefsByDate(level: number): Observable<Object> {
        const payload = {
            "reduce": true,
            "group": true,
            "group_level": level
        }
        const url = `${this._couchdbUrl}/${this._couchdbDatabase}/_design/${this._couchdbDesign}/_view/filterAeronefByDate/`;
        return this._http.post(url, payload, this.httpOptions);
    }

    /* get all docs from couchDB view 'filterCanopyModel' */
    getCanopyModels(): Observable<Object> {
        const payload = {
            "reduce": true,
            "group": true
        }
        const url = `${this._couchdbUrl}/${this._couchdbDatabase}/_design/${this._couchdbDesign}/_view/filterCanopyModel/`;
        return this._http.post(url, payload, this.httpOptions);
    }

    /* get all docs from couchDB view 'filterCanopyModelByDate' */
    getCanopyModelsByDate(level: number): Observable<Object> {
        const payload = {
            "reduce": true,
            "group": true,
            "group_level": level
        }
        const url = `${this._couchdbUrl}/${this._couchdbDatabase}/_design/${this._couchdbDesign}/_view/filterCanopyModelByDate/`;
        return this._http.post(url, payload, this.httpOptions);
    }

    /* get all docs from couchDB view 'filterCanopySize' */
    getCanopySizes(): Observable<Object> {
        const payload = {
            "reduce": true,
            "group": true
        }
        const url = `${this._couchdbUrl}/${this._couchdbDatabase}/_design/${this._couchdbDesign}/_view/filterCanopySize/`;
        return this._http.post(url, payload, this.httpOptions);
    }

    /* get all docs from couchDB view 'filterCanopySizeByDate' */
    getCanopySizesByDate(level: number): Observable<Object> {
        const payload = {
            "reduce": true,
            "group": true,
            "group_level": level
        }
        const url = `${this._couchdbUrl}/${this._couchdbDatabase}/_design/${this._couchdbDesign}/_view/filterCanopySizeByDate/`;
        return this._http.post(url, payload, this.httpOptions);
    }

    /* get all docs from couchDB view 'allDropZones' */
    getDropZones(): Observable<Object> {
        const payload = {
            "reduce": true,
            "group": true
        }
        const url = `${this._couchdbUrl}/${this._couchdbDatabase}/_design/${this._couchdbDesign}/_view/allDropZones/`;
        return this._http.post(url, payload, this.httpOptions);
    }

    /* get all docs from couchDB view 'allDropZonesByDate' */
    getDropZonesByDate(level: number): Observable<Object> {
        const payload = {
            "reduce": true,
            "group": true,
            "group_level": level
        }
        const url = `${this._couchdbUrl}/${this._couchdbDatabase}/_design/${this._couchdbDesign}/_view/allDropZonesByDate/`;
        return this._http.post(url, payload, this.httpOptions);
    }

    /* get all docs from couchDB view 'allJumps' */
    getTotalJumps(): Observable<Object> {
        const payload = {
            "reduce": true,
            "group": true,
            "group_level": 1
        }
        const url = `${this._couchdbUrl}/${this._couchdbDatabase}/_design/${this._couchdbDesign}/_view/allJumps/`;
        return this._http.post(url, payload, this.httpOptions);
    }

    /* get all docs from couchDB view 'allDevices' */
    getDeviceActivities(deviceId: string, limit: number, start: number, end: number): Observable<Object> {
        const payload = {
            "selector": {
                "type": {
                    "$eq": "activity"
                },
                "device_id": {
                    "$eq": deviceId
                },
                "created_time": {
                    "$gte": start,
                    "$lte": end
                }
            },
            "fields": [
                "created_time",
                "device_id",
                "values"
            ],
            "sort": [
                {
                    "created_time": "desc"
                }
            ],
            "limit": limit
        }
        //const url = this._couchdbUrl + '/' + this._couchdbDatabase + '/_find';
        const url = `${this._couchdbUrl}/material_grow/_find`;
        return this._http.post(url, payload, this.httpOptions);
    }

    /* get all docs from couchDB view 'getDevicesActivities' */
    getDevicesActivities(key: string, limit: number, start: any, end: any): Observable<Object> {
        /*
        const payload = {
            "start_key": [deviceId, end],
            "end_key": [deviceId, start],
            "descending": true,
            "limit": limit,
            "reduce": false
        }
        const url = this._couchdbUrl + '/' + this._couchdbDatabase + '/_design/' + this._couchdbDesign + '/_view/allActivitiesByDevice/';
        */
        const payload = {
            "start_key": [key, 1, start],
            "end_key": [key, 1, end],
            "limit": limit,
            "descending": true,
            "include_docs": true,
            "reduce": false
        }
        const url = `${this._couchdbUrl}/netgrowing/_design/app/_view/getDevicesActivities`;
        return this._http.post(url, payload, this.httpOptions);
    }

}