<%#
 Copyright 2013-2019 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
<%_
const query = generateEntityQueries(relationships, entityInstance, dto);
const queries = query.queries;
const variables = query.variables;
let hasManyToMany = query.hasManyToMany;
_%>
import { Component, OnInit<% if (fieldsContainImageBlob) { %>, ElementRef<% } %> } from '@angular/core';
import { HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { FormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';
<%_ if (queries && queries.length > 0) { _%>
import { filter, map } from 'rxjs/operators';
<%_ } _%>
<%_ if ( fieldsContainDate ) { _%>
import * as moment from 'moment';
    <%_ if ( fieldsContainInstant || fieldsContainZonedDateTime ) { _%>
import { DATE_TIME_FORMAT } from 'app/shared/constants/input.constants';
    <%_ } _%>
<%_ } _%>
<%_ if (queries && queries.length > 0 || fieldsContainBlob) { _%>
import { <% if (fieldsContainBlob || queries && queries.length > 0) { %>JhiAlertService, <% } %><% if (fieldsContainBlob) { %>JhiDataUtils<% } %> } from '<%= styleLibrary === 'bootstrap' ? 'ng-jhipster' : 'ng-fedhipster' %>';
<%_ } _%>
import { I<%= entityAngularName %>, <%= entityAngularName %> } from 'app/shared/model/<%= entityModelFileName %>.model';
import { <%= entityAngularName %>Service } from './<%= entityFileName %>.service';
<%_
let hasRelationshipQuery = false;
Object.keys(differentRelationships).forEach(key => {
    const hasAnyRelationshipQuery = differentRelationships[key].some(rel =>
        (rel.relationshipType === 'one-to-one' && rel.ownerSide === true && rel.otherEntityName !== 'user')
            || rel.relationshipType !== 'one-to-many'
    );
    if (hasAnyRelationshipQuery) {
        hasRelationshipQuery = true;
    }
    if (differentRelationships[key].some(rel => rel.relationshipType !== 'one-to-many')) {
        const uniqueRel = differentRelationships[key][0];
        if (uniqueRel.otherEntityAngularName !== entityAngularName) {
            if (uniqueRel.otherEntityAngularName === 'User') {
_%>
import { I<%= uniqueRel.otherEntityAngularName %>, <%= uniqueRel.otherEntityAngularName%>Service } from 'app/core';
<%_         } else { _%>
import { I<%= uniqueRel.otherEntityAngularName %> } from 'app/shared/model/<%= uniqueRel.otherEntityModelName %>.model';
import { <%= uniqueRel.otherEntityAngularName%>Service } from 'app/entities/<%= uniqueRel.otherEntityPath %>';
<%_         }
        }
    }
}); _%>

@Component({
    selector: '<%= jhiPrefixDashed %>-<%= entityFileName %>-update',
    templateUrl: './<%= entityFileName %>-update.component.html'
})
export class <%= entityAngularName %>UpdateComponent implements OnInit {

    <%= entityInstance %>: I<%= entityAngularName %>;
    isSaving: boolean;
<%_
for ( const idx in variables ) { %>
    <%- variables[idx] %>
<%_ } _%>
<%_ for ( idx in fields ) {
    const fieldName = fields[idx].fieldName;
    const fieldType = fields[idx].fieldType;
        if ( fieldType === 'LocalDate' ) { _%>
    <%= fieldName %>Dp: any;
        <%_ } _%>
<%_ } _%>

    editForm = this.fb.group({
        id: [],
<%_ for (idx in fields) {
    const fieldName = fields[idx].fieldName;
    const fieldType = fields[idx].fieldType;
    const fieldTypeBlobContent = fields[idx].fieldTypeBlobContent; _%>
        <%= fieldName %>: [<% if (fields[idx].fieldValidate === true) { %>null,[<% if(fields[idx].fieldValidateRules.includes('required')) { %>Validators.required,<% } %><% if(fields[idx].fieldValidateRules.includes('minlength')) { %>Validators.minLength(<%= fields[idx].fieldValidateRulesMinlength %>),<% } %><% if(fields[idx].fieldValidateRules.includes('maxlength')) { %>Validators.maxLength(<%= fields[idx].fieldValidateRulesMaxlength %>),<% } %><% if(fields[idx].fieldValidateRules.includes('min')) { %>Validators.min(<%= fields[idx].fieldValidateRulesMin %>),<% } %><% if(fields[idx].fieldValidateRules.includes('max')) { %>Validators.max(<%= fields[idx].fieldValidateRulesMax %>),<% } %><% if(fields[idx].fieldValidateRules.includes('pattern')) { %>Validators.pattern('<%= fields[idx].fieldValidateRulesPattern %>'),<% } %>]<% } %>],
    <%_ if (['byte[]', 'ByteBuffer'].includes(fieldType) && fieldTypeBlobContent !== 'text') { _%>
        <%= fieldName %>ContentType: [],
    <%_ } _%>
<%_ } _%>
<%_ for (idx in relationships) {
    const relationshipType = relationships[idx].relationshipType;
    const ownerSide = relationships[idx].ownerSide;
    const otherEntityName = relationships[idx].otherEntityName;
    const otherEntityNamePlural = relationships[idx].otherEntityNamePlural;
    const otherEntityNameCapitalized = relationships[idx].otherEntityNameCapitalized;
    const relationshipName = relationships[idx].relationshipName;
    const relationshipNameHumanized = relationships[idx].relationshipNameHumanized;
    const relationshipFieldName = relationships[idx].relationshipFieldName;
    const relationshipFieldNamePlural = relationships[idx].relationshipFieldNamePlural;
    const otherEntityField = relationships[idx].otherEntityField;
    const otherEntityFieldCapitalized = relationships[idx].otherEntityFieldCapitalized;
    const relationshipRequired = relationships[idx].relationshipRequired;
    const translationKey = `${i18nKeyPrefix}.${relationshipName}`; _%>
    <%_ if (relationshipType === 'many-to-one' || (relationshipType === 'one-to-one' && ownerSide === true)) { _%>
        <%_ if (dto === 'no') { _%>
        <%=relationshipName %>: [<% if (relationshipRequired) { %>null,Validators.required<% } %>],
        <%_ } else { _%>
        <%=relationshipName %>Id: [<% if (relationshipRequired) { %>null,Validators.required<% } %>],
        <%_ } _%>
    <%_ } else if (relationshipType === 'many-to-many' && relationships[idx].ownerSide === true) { _%>
        <%=relationshipFieldNamePlural %>: [<% if (relationshipRequired) { %>null,Validators.required<% } %>],
    <%_ } _%>
<%_ } _%>

    });

    constructor(
<%_ if (fieldsContainBlob) { _%>
        protected dataUtils: JhiDataUtils,
<%_ } _%>
<%_ if (fieldsContainBlob || queries && queries.length > 0) { _%>
        protected jhiAlertService: JhiAlertService,
<%_ } _%>
        protected <%= entityInstance %>Service: <%= entityAngularName %>Service,
<%_ Object.keys(differentRelationships).forEach(key => {
    if (differentRelationships[key].some(rel => rel.relationshipType !== 'one-to-many')) {
        const uniqueRel = differentRelationships[key][0];
        if (uniqueRel.otherEntityAngularName !== entityAngularName) { _%>
        protected <%= uniqueRel.otherEntityName %>Service: <%= uniqueRel.otherEntityAngularName %>Service,
<%_
        }
    }
}); _%>
<%_ if (fieldsContainImageBlob) { _%>
        protected elementRef: ElementRef,
<%_ } _%>
        protected activatedRoute: ActivatedRoute,
        private fb: FormBuilder
    ) {
    }

    ngOnInit() {
        this.isSaving = false;
        this.activatedRoute.data.subscribe(({<%= entityInstance %>}) => {
            this.updateForm(<%= entityInstance %>);
            this.<%= entityInstance %> = <%= entityInstance %>;
        });
<%_ for (idx in queries) { _%>
        <%- queries[idx] %>
<%_ } _%>
    }

    updateForm(<%= entityInstance %>: I<%= entityAngularName %>) {
        this.editForm.patchValue({
            id: <%= entityInstance %>.id,
<%_ for (idx in fields) {
    const fieldName = fields[idx].fieldName;
    const fieldType = fields[idx].fieldType;
    const fieldTypeBlobContent = fields[idx].fieldTypeBlobContent;
_%>
    <%_ if (['Instant', 'ZonedDateTime'].includes(fieldType)) { _%>
            <%= fieldName %>: <%= entityInstance %>.<%= fieldName %> != null ? <%= entityInstance %>.<%= fieldName %>.format(DATE_TIME_FORMAT) : null,
    <%_ } else if (['byte[]', 'ByteBuffer'].includes(fieldType) && fieldTypeBlobContent !== 'text') { _%>
            <%= fieldName %>: <%= entityInstance %>.<%= fieldName %>,
            <%= fieldName %>ContentType: <%= entityInstance %>.<%= fieldName %>ContentType,
    <%_ } else { _%>
            <%= fieldName %>: <%= entityInstance %>.<%= fieldName %>,
    <%_ } _%>
<%_ } _%>
<%_ for (idx in relationships) {
    const relationshipType = relationships[idx].relationshipType;
    const ownerSide = relationships[idx].ownerSide;
    const otherEntityName = relationships[idx].otherEntityName;
    const otherEntityNamePlural = relationships[idx].otherEntityNamePlural;
    const otherEntityNameCapitalized = relationships[idx].otherEntityNameCapitalized;
    const relationshipName = relationships[idx].relationshipName;
    const relationshipNameHumanized = relationships[idx].relationshipNameHumanized;
    const relationshipFieldName = relationships[idx].relationshipFieldName;
    const relationshipFieldNamePlural = relationships[idx].relationshipFieldNamePlural;
    const otherEntityField = relationships[idx].otherEntityField;
    const otherEntityFieldCapitalized = relationships[idx].otherEntityFieldCapitalized;
    const relationshipRequired = relationships[idx].relationshipRequired;
    const translationKey = `${i18nKeyPrefix}.${relationshipName}`; _%>
    <%_ if (relationshipType === 'many-to-one' || (relationshipType === 'one-to-one' && ownerSide === true)) { _%>
        <%_ if (dto === 'no') { _%>
            <%=relationshipName %>: <%= entityInstance %>.<%=relationshipFieldName %>,
        <%_ } else { _%>
            <%=relationshipName %>Id: <%= entityInstance %>.<%=relationshipFieldName %>Id,
        <%_ } _%>
    <%_ } else if (relationshipType === 'many-to-many' && relationships[idx].ownerSide === true) { _%>
            <%=relationshipFieldNamePlural %>: <%=entityInstance %>.<%=relationshipFieldNamePlural %>,
    <%_ } _%>
<%_ } _%>
        });
    }

<%_ if (fieldsContainBlob) { _%>
    byteSize(field) {
        return this.dataUtils.byteSize(field);
    }

    openFile(contentType, field) {
        return this.dataUtils.openFile(contentType, field);
    }

    setFileData(event, field: string, isImage) {
        return new Promise((resolve, reject) => {
            if (event && event.target && event.target.files && event.target.files[0]) {
                const file = event.target.files[0];
                if (isImage && !/^image\//.test(file.type)) {
                    reject(`File was expected to be an image but was found to be ${file.type}`);
                } else {
                    const filedContentType: string = field + 'ContentType';
                    this.dataUtils.toBase64(file, (base64Data) => {
                        this.editForm.patchValue({
                            [field]: base64Data,
                            [filedContentType]: file.type
                        });
                    });
                }
            } else {
                reject(`Base64 data was not set as file could not be extracted from passed parameter: ${event}`);
            }
        }).then(() => console.log('blob added'),// sucess
                this.onError);
    }

    <%_ if (fieldsContainImageBlob) { _%>
    clearInputImage(field: string, fieldContentType: string, idInput: string) {
        this.editForm.patchValue({
            [field]: null,
            [fieldContentType]: null
        });
        if (this.elementRef && idInput && this.elementRef.nativeElement.querySelector('#' + idInput)) {
            this.elementRef.nativeElement.querySelector('#' + idInput).value = null;
        }
    }

    <%_ } _%>
<%_ } _%>
    previousState() {
        window.history.back();
    }

    save() {
        this.isSaving = true;
        const <%= entityInstance %> = this.createFromForm();
        if (<%= entityInstance %>.id !== undefined) {
            this.subscribeToSaveResponse(
                this.<%= entityInstance %>Service.update(<%= entityInstance %>));
        } else {
            this.subscribeToSaveResponse(
                this.<%= entityInstance %>Service.create(<%= entityInstance %>));
        }
    }

    private createFromForm(): I<%= entityAngularName %> {
        const entity = {
                       ...new <%= entityAngularName %>(),
            id: this.editForm.get(['id']).value,
    <%_ for (idx in fields) {
        const fieldName = fields[idx].fieldName;
        const fieldType = fields[idx].fieldType;
        const fieldTypeBlobContent = fields[idx].fieldTypeBlobContent;
    _%>
        <%_ if (['Instant', 'ZonedDateTime'].includes(fieldType)) { _%>
            <%= fieldName %>: this.editForm.get(['<%= fieldName %>']).value != null ? moment(this.editForm.get(['<%= fieldName %>']).value, DATE_TIME_FORMAT) : undefined,
        <%_ } else if (['byte[]', 'ByteBuffer'].includes(fieldType) && fieldTypeBlobContent !== 'text') { _%>
            <%= fieldName %>ContentType: this.editForm.get(['<%= fieldName %>ContentType']).value,
            <%= fieldName %>: this.editForm.get(['<%= fieldName %>']).value,
        <%_ } else { _%>
            <%= fieldName %>: this.editForm.get(['<%= fieldName %>']).value,
        <%_ } _%>
    <%_ } _%>
    <%_ for (idx in relationships) {
        const relationshipType = relationships[idx].relationshipType;
        const ownerSide = relationships[idx].ownerSide;
        const otherEntityName = relationships[idx].otherEntityName;
        const otherEntityNamePlural = relationships[idx].otherEntityNamePlural;
        const otherEntityNameCapitalized = relationships[idx].otherEntityNameCapitalized;
        const relationshipName = relationships[idx].relationshipName;
        const relationshipNameHumanized = relationships[idx].relationshipNameHumanized;
        const relationshipFieldName = relationships[idx].relationshipFieldName;
        const relationshipFieldNamePlural = relationships[idx].relationshipFieldNamePlural;
        const otherEntityField = relationships[idx].otherEntityField;
        const otherEntityFieldCapitalized = relationships[idx].otherEntityFieldCapitalized;
        const relationshipRequired = relationships[idx].relationshipRequired;
        const translationKey = `${i18nKeyPrefix}.${relationshipName}`; _%>
        <%_ if (relationshipType === 'many-to-one' || (relationshipType === 'one-to-one' && ownerSide === true)) { _%>
            <%_ if (dto === 'no') { _%>
            <%= relationshipName %>: this.editForm.get(['<%= relationshipName %>']).value,
            <%_ } else { _%>
            <%= relationshipName %>Id: this.editForm.get(['<%= relationshipName %>Id']).value,
            <%_ } _%>
        <%_ } else if (relationshipType === 'many-to-many' && relationships[idx].ownerSide === true) { _%>
            <%= relationshipFieldNamePlural %>: this.editForm.get(['<%= relationshipFieldNamePlural %>']).value,
        <%_ } _%>
<%_ } _%>
        }
        return entity;
    }

    protected subscribeToSaveResponse(result: Observable<HttpResponse<I<%= entityAngularName %>>>) {
        result.subscribe((res: HttpResponse<I<%= entityAngularName %>>) =>
            this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError());
    }

    protected onSaveSuccess() {
        this.isSaving = false;
        this.previousState();
    }

    protected onSaveError() {
        this.isSaving = false;
    }
<%_ if (fieldsContainBlob || queries && queries.length > 0) { _%>
    protected onError(errorMessage: string) {
        this.jhiAlertService.error(errorMessage, null, null);
    }
<%_ } _%>
<%_
const entitiesSeen = [];
for (idx in relationships) {
    const otherEntityNameCapitalized = relationships[idx].otherEntityNameCapitalized;
    if (relationships[idx].relationshipType !== 'one-to-many' && !entitiesSeen.includes(otherEntityNameCapitalized)) {
_%>

    track<%= otherEntityNameCapitalized %>ById(index: number, item: I<%= relationships[idx].otherEntityAngularName %>) {
        return item.id;
    }
<%_ entitiesSeen.push(otherEntityNameCapitalized); } } _%>
<%_ if (hasManyToMany) { _%>

    getSelected(selectedVals: Array<any>, option: any) {
        if (selectedVals) {
            for (let i = 0; i < selectedVals.length; i++) {
                if (option.id === selectedVals[i].id) {
                    return selectedVals[i];
                }
            }
        }
        return option;
    }
<%_ } _%>

    shouldShowError(formControl) {
        return formControl.invalid && (formControl.dirty || formControl.touched);
    }
}
