<template>
  <div class="{{component}}-editor">

    <!-- SYSTEM-BUILDER-input-row -->

    <div class="errorMessage" v-if="errorMessage != ''">{{errorMessage}}</div>
    <div class="action-buttons">
      <button class="btn" @click="close()">Cancel</button>
      <button class="btn btn-secondary" :disabled="!isComplete" @click="isComplete && save{{Component}}()">Save</button>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import { {{component}}Service } from './{{component}}Service';
import { {{Component}}Config } from './{{component}}Types';

@Component
export default class {{Component}}Editor extends Vue {
  @Prop() private {{component}}_id!: string;
  private {{component}}: {{Component}}Config = {
    // SYSTEM-BUILDER-init-props
  };
  private loading: boolean = false;
  private errorMessage: string = '';

  get isComplete() {
    return true;
  }

  private close() {
    this.$emit('close-editor');
  }

  private mounted() {
    this.loadDetails();
  }

  private loadDetails() {
    this.loading = true;
    this.errorMessage = '';
    {{component}}Service.get{{Component}}(this.{{component}}_id).then((res: {{Component}}Config) => {
      this.loading = false;
      this.errorMessage = '';
      this.{{component}} = res;
    }).catch(this.handleError.bind(this));
  }

  private save{{Component}}() {
    this.loading = true;
    this.errorMessage = '';
    // either create or update...
    if (this.{{component}}.{{component}}_id === '') {
      {{component}}Service.create{{Component}}(this.{{component}}).then(() => {
        // success
        this.loading = false;
        this.errorMessage = '';
        this.close();
      }).catch(this.handleError.bind(this));
    } else {
      {{component}}Service.update{{Component}}(this.{{component}}.{{component}}_id, this.{{component}}).then(() => {
        // success
        this.loading = false;
        this.errorMessage = '';
        this.close();
      }).catch(this.handleError.bind(this));
    }
  }

  private handleError(err: any) {
    // error
    this.loading = false;
    this.errorMessage = err.message;
  }
}
</script>

<style scoped lang="css">
.errorMessage {
  color: red;
}
</style>
