jrvlima
1/6/2018 - 3:01 PM

Fetching Attachment

Fetching Attachment

import {Component, ViewChild} from '@angular/core';
import {AlertController, LoadingController, NavController, NavParams, Platform} from 'ionic-angular';
import {SedimentGeneratingActivitiesProvider} from "../../../providers/sediment-generating-activities/sediment-generating-activities";
import {TypeForm} from "../../generic/form-detail/type-form";
import {
  ActionSedimentRetention,
  ErosionControlSolution,
  ErosionSource,
  FloodOccurrence,
  SedimentGeneratingActivities
} from "../../../models/sediment-generating-activities.model";
import {Camera} from "@ionic-native/camera";
import {Geolocation} from '@ionic-native/geolocation';
import {NgForm} from "@angular/forms";
import {FormValidationState} from "../../../models/participant.model";
import {AlertsProvider} from "../../../providers/alerts/alerts";
import {ParticipantProvider} from "../../../providers/participant/participant";
import {DatabaseProvider} from "../../../providers/database/database";

@Component({
  selector: 'sediment-generating-activities-create',
  templateUrl: 'sediment-generating-activities-create.html',
})
export class SedimentGeneratingActivitiesCreateComponent extends TypeForm {

  displayErosionSources: boolean;
  displayErosionControlSolution: boolean;
  displayActionSedimentRetention: boolean;
  displayFloodOccurrence: boolean;
  sedimentGeneratingActivities: SedimentGeneratingActivities;
  erosionSources: Array<ErosionSource>;
  floodOccurrences: Array<FloodOccurrence>;
  erosionControlSolutions: Array<ErosionControlSolution>;
  actionSedimentRetentions: Array<ActionSedimentRetention>;
  loading;
  @ViewChild('sedimentGeneratingActivitiesForm') public form: NgForm;

  constructor(protected platform: Platform,
              protected navCtrl: NavController,
              protected geoLocation: Geolocation,
              protected camera: Camera,
              protected navParams: NavParams,
              private participantProvider: ParticipantProvider,
              protected alert: AlertsProvider,
              protected loadingCtrl: LoadingController,
              protected alertController: AlertController,
              protected databaseProvider: DatabaseProvider,
              protected sedimentGeneratingActivitiesProvider: SedimentGeneratingActivitiesProvider) {

    super(platform, navCtrl, geoLocation, camera, alert, loadingCtrl,
      alertController, sedimentGeneratingActivitiesProvider, navParams);

    this.sedimentGeneratingActivities = new SedimentGeneratingActivities();
    this.erosionSources = [];
    this.erosionControlSolutions = [];
    this.actionSedimentRetentions = [];
    this.floodOccurrences = [];

    this.initData();
  }

  initData() {
    const loading = this.loadingCtrl.create({
      content: 'Buscando informações'
    });
    loading.present();
    return this.sedimentGeneratingActivitiesProvider.findByParticipant(this.participant.id)
      .then(data => {
        if (this.haveSedimentGeneratingActivities(data)) {
          this.assignSedimentGeneratingActivities(data);
          return this.databaseProvider.db.createIndex({index: {fields: ['data.sedimentGeneratingActivity', '_id']}})
            .then(() => {
              return [
                this.getErosionSources(),
                this.getErosionControlSolutions(),
                this.getActionSedimentRetentions(),
                this.getFloodOccurrences()
              ].reduce((p, f) => p.then(f), Promise.resolve())
            });
        } else {
          return this.saveDiagnosticRecord();
        }
      })
      .catch((e) => {
        this.showErrorAlert(e);
      })
      .then(() => {
        loading.dismiss();
      });
  }

  private assignSedimentGeneratingActivities(data) {
    Object.assign(this.sedimentGeneratingActivities, data.sedimentGeneratingActivities[0]);
  }

  private haveSedimentGeneratingActivities(data) {
    return data && data.sedimentGeneratingActivities && data.sedimentGeneratingActivities.length > 0;
  }

  private getErosionSources() {
    const promises: Array<any> = new Array<any>();
    return this.databaseProvider.db.rel.findHasMany('erosionSource', 'sedimentGeneratingActivity',
      this.sedimentGeneratingActivities.id)
      .then((data) => {
        Object.assign(this.erosionSources, data.erosionSources);
        this.erosionSources.forEach((erosionSource) => {
          let bindData = (data) => {
            erosionSource.imageBase64 = data;
          };
          promises.push(this.sedimentGeneratingActivitiesProvider
            .getAttachment('erosionSource', erosionSource.id, `${erosionSource.id}.jpeg`, bindData));
        });
        return promises.reduce((p, f) => p.then(f), Promise.resolve());
      });
  }

  private getErosionControlSolutions() {
    const promises: Array<any> = new Array<any>();
    return this.databaseProvider.db.rel.findHasMany('erosionControlSolution', 'sedimentGeneratingActivity',
      this.sedimentGeneratingActivities.id)
      .then((data) => {
        Object.assign(this.erosionControlSolutions, data.erosionControlSolutions);
        this.erosionControlSolutions.forEach((erosionControlSolution) => {
          let bindData = (data) => {
            erosionControlSolution.imageBase64 = data;
          };
          promises.push(this.sedimentGeneratingActivitiesProvider
            .getAttachment('erosionControlSolution', erosionControlSolution.id, `${erosionControlSolution.id}.jpeg`,
              bindData));
        });
        return promises.reduce((p, f) => p.then(f), Promise.resolve());
      })
  }

  private getActionSedimentRetentions() {
    const promises: Array<any> = new Array<any>();
    return this.databaseProvider.db.rel.findHasMany('actionSedimentRetention', 'sedimentGeneratingActivity',
      this.sedimentGeneratingActivities.id)
      .then((data) => {
        Object.assign(this.actionSedimentRetentions, data.actionSedimentRetentions);
        this.actionSedimentRetentions.forEach((actionSedimentRetention) => {
          let bindData = (data) => {
            actionSedimentRetention.imageBase64 = data;
          };
          promises.push(this.sedimentGeneratingActivitiesProvider
            .getAttachment('actionSedimentRetention', actionSedimentRetention.id, `${actionSedimentRetention.id}.jpeg`,
              bindData));
        });
        return promises.reduce((p, f) => p.then(f), Promise.resolve());
      })
  }

  private getFloodOccurrences() {
    const promises: Array<any> = new Array<any>();
    return this.databaseProvider.db.rel.findHasMany('floodOccurrence', 'sedimentGeneratingActivity',
      this.sedimentGeneratingActivities.id)
      .then((data) => {
        console.dir(data);
        Object.assign(this.floodOccurrences, data.floodOccurrences);
        this.floodOccurrences.forEach((floodOccurrence) => {
          let bindData = (data) => {
            floodOccurrence.imageBase64 = data;
          };
          promises.push(this.sedimentGeneratingActivitiesProvider
            .getAttachment('floodOccurrence', floodOccurrence.id, `${floodOccurrence.id}.jpeg`, bindData));
        });
        return promises.reduce((p, f) => p.then(f), Promise.resolve());
      });
  }

  addErosionControlSolution() {
    this.displayErosionControlSolution = true;
    this.sedimentGeneratingActivities.implementedSolutionsExist = 'Sim';
    let number = this.erosionControlSolutions.length + 1;
    const sourceName = `Erosão - Solução de Controle ${number}`;
    let erosionControlSolution = new ErosionControlSolution(sourceName, this.sedimentGeneratingActivities);
    erosionControlSolution.order = number;
    this.erosionControlSolutions.push(erosionControlSolution);
  }

  removeErosionControlSolution() {
    this.erosionControlSolutions.pop();
    if (this.erosionControlSolutions.length === 0) {
      this.sedimentGeneratingActivities.implementedSolutionsExist = 'Não';
    }
  }

  addLocationsWithErosion() {
    this.displayErosionSources = true;
    this.sedimentGeneratingActivities.locationsWithErosion = 'Sim';
    let number = this.erosionSources.length + 1;
    const sourceName = `Erosão ${number}`;
    let erosionSource = new ErosionSource(sourceName, this.sedimentGeneratingActivities);
    erosionSource.order = number;
    this.erosionSources.push(erosionSource);
  }

  removeLocationsWithErosion() {
    this.erosionSources.pop();
    if (this.erosionSources.length === 0) {
      this.sedimentGeneratingActivities.locationsWithErosion = 'Não';
    }
  }

  addActionSedimentRetention() {
    this.displayActionSedimentRetention = true;
    this.sedimentGeneratingActivities.retentionActions = 'Sim';
    let number = this.actionSedimentRetentions.length + 1;
    const sourceName = `Ação Retenção de Sedimento ${number}`;
    let actionSedimentRetention = new ActionSedimentRetention(sourceName, this.sedimentGeneratingActivities);
    actionSedimentRetention.order = number;
    this.actionSedimentRetentions.push(actionSedimentRetention);
  }

  removeActionSedimentRetention() {
    this.actionSedimentRetentions.pop();
    if (this.actionSedimentRetentions.length === 0) {
      this.sedimentGeneratingActivities.retentionActions = 'Não';
    }
  }

  addFloodOccurrence() {
    this.displayFloodOccurrence = true;
    this.sedimentGeneratingActivities.floodOccurrence = 'Sim';
    let number = this.floodOccurrences.length + 1;
    const sourceName = `Ocorrência de Enxurrada ${number}`;
    let floodOccurrence = new FloodOccurrence(sourceName, this.sedimentGeneratingActivities);
    floodOccurrence.order = number;
    this.floodOccurrences.push(floodOccurrence);
  }

  removeFloodOccurrence() {
    this.floodOccurrences.pop();
    if (this.floodOccurrences.length === 0) {
      this.sedimentGeneratingActivities.floodOccurrence = 'Não';
    }
  }

  saveInformation() {
    if (!this.sedimentGeneratingActivities.participant) {
      this.sedimentGeneratingActivities.participant = this.participant;
    }
    if (!this.sedimentGeneratingActivities.agentUsername) {
      this.sedimentGeneratingActivities.agentUsername = this.participant.agentUsername;
    }

    return [
      this.saveErosionSources(),
      this.saveErosionControlSolutionSources(),
      this.saveActionSedimentRetentionSources(),
      this.saveFloodOccurrenceSources()
    ].reduce((p, f) => p.then(f), Promise.resolve())
      .then(() => {
        return this.saveDiagnosticRecord();
      })
      .catch((e) => {
        this.showErrorAlert(e);
      })
  }

  saveDiagnosticRecord() {
    return this.sedimentGeneratingActivitiesProvider.save(this.sedimentGeneratingActivities);
  }

  private saveErosionSources() {
    const promises: Array<any> = new Array<any>();
    this.erosionSources.forEach((erosionSource) => {
      erosionSource.imageBase64 = '';
      promises.push(this.databaseProvider.save(erosionSource, 'erosionSource'));
    });
    return promises.reduce((p, f) => p.then(f), Promise.resolve());
  }

  private saveErosionControlSolutionSources() {
    const promises: Array<any> = new Array<any>();
    this.erosionControlSolutions.forEach((erosionControlSolution) => {
      erosionControlSolution.imageBase64 = '';
      promises.push(this.databaseProvider.save(erosionControlSolution, 'erosionControlSolution'));
    });
    return promises.reduce((p, f) => p.then(f), Promise.resolve());
  }

  private saveActionSedimentRetentionSources() {
    const promises: Array<any> = new Array<any>();
    this.actionSedimentRetentions.forEach((actionSedimentRetention) => {
      actionSedimentRetention.imageBase64 = '';
      promises.push(this.databaseProvider.save(actionSedimentRetention, 'actionSedimentRetention'));
    });
    return promises.reduce((p, f) => p.then(f), Promise.resolve());
  }

  private saveFloodOccurrenceSources() {
    const promises: Array<any> = new Array<any>();
    this.floodOccurrences.forEach((floodOccurrence) => {
      floodOccurrence.imageBase64 = '';
      promises.push(this.databaseProvider.save(floodOccurrence, 'floodOccurrence'));
    });
    return promises.reduce((p, f) => p.then(f), Promise.resolve());
  }

  isFormComplete(data) {
    return data.participants[0].formsToValidate.sedimentGeneratingActivities === 'Complete';
  }

  saveForm() {
    let status = this.isFormValid();

    return this.saveInformation()
      .then(() => {
        this.participant.formsToValidate = this.participant.formsToValidate || new FormValidationState();
        this.participant.formsToValidate.sedimentGeneratingActivities = status;
        return this.participantProvider.add(this.participant);
      });
  }

  private isFormValid() {
    let isValid = true;

    this.erosionSources.forEach(value => {
      isValid = isValid && value.erosionType != '';
      isValid = isValid && value.erosionDimensions != '';
    });

    return isValid && this.form.valid ? 'Complete' : this.form.dirty || this.form.touched ? 'Partial' : 'None';
  }

}