<h2>{{mode === 'new' ? 'Add new sample' : 'Edit sample'}}</h2>

<rb-loading-spinner *ngIf="loading; else content"></rb-loading-spinner>

<ng-template #content>

<!--BASE-->

  <form #sampleForm="ngForm" *ngIf="view.base">
    <div class="sample">
      <div>
        <rb-form-input name="materialname" label="product name" [rbDebounceTime]="0" [rbInitialOpen]="true"
                       [rbFormInputAutocomplete]="autocomplete.bind(this, materialNames)" appValidate="stringOf"
                       (keydown)="preventDefault($event)" (ngModelChange)="findMaterial($event)" ngModel
                       [appValidateArgs]="[materialNames]" required [(ngModel)]="material.name" [autofocus]="true"
                       *ngIf="mode === 'new' || (baseSample.material && baseSample.material.name !== undefined)"
                       title="trade name of the material, eg. Ultradur B4300 G6">
          <ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
          <ng-template rbFormValidationMessage="failure">Unknown material, add properties for new material</ng-template>
        </rb-form-input>
        <rb-icon-button class="set-new-material space-below" icon="add" mode="secondary"
                        (click)="setNewMaterial(!newMaterial)"
                        *ngIf="mode === 'new' || (baseSample.material && baseSample.material.name !== undefined)">
          New material
        </rb-icon-button>
      </div>

      <div class="material shaded-container" *ngIf="newMaterial" [@inOut]>
        <h4>Material properties</h4>
        <rb-form-input name="supplier" label="supplier"
                       [rbFormInputAutocomplete]="autocomplete.bind(this, d.arr.materialSuppliers)"
                       [rbDebounceTime]="0" [rbInitialOpen]="true" appValidate="string" required
                       [(ngModel)]="material.supplier" #supplierInput="ngModel"
                       (focusout)="checkTypo($event, 'materialSuppliers', 'supplier', modalWarning)"
                       title="material supplier, eg. BASF">
          <ng-template rbFormValidationMessage="failure">{{supplierInput.errors.failure}}</ng-template>
        </rb-form-input>
        <rb-form-input name="group" label="group"
                       [rbFormInputAutocomplete]="autocomplete.bind(this, d.arr.materialGroups)"
                       [rbDebounceTime]="0" [rbInitialOpen]="true" appValidate="string" required
                       [(ngModel)]="material.group" #groupInput="ngModel"
                       (focusout)="checkTypo($event, 'materialGroups', 'group', modalWarning)"
                       title="chemical material type, eg. PA66">
          <ng-template rbFormValidationMessage="failure">{{groupInput.errors.failure}}</ng-template>
        </rb-form-input>
        <ng-template #modalWarning>
          <rb-alert alertTitle="Warning" type="warning" okBtnLabel="Use suggestion" cancelBtnLabel="Keep value">
            The specified {{modalText.list}} could not be found in the list. <br>
            Did you mean {{modalText.suggestion}}?
          </rb-alert>
        </ng-template>
        <rb-array-input [(ngModel)]="material.numbers" name="materialNumbers" [pushTemplate]="''">
          <rb-form-input *rbArrayInputItem="let item" [rbArrayInputListener]="'materialNumber'" [index]="item.i"
                         label="material number" appValidate="string" [name]="'materialNumber-' + item.i"
                         [ngModel]="item.value" title="Bosch material part number, eg. 5515753021"></rb-form-input>
        </rb-array-input>
        <rb-form-select name="propertiesSelect" label="Type" title="=overall material group specific properties"
                        [(ngModel)]="material.properties.material_template">
          <option *ngFor="let m of d.latest.materialTemplates" [value]="m._id">{{m.name}}</option>
        </rb-form-select>
        <rb-form-input *ngFor="let parameter of
                         d.id.materialTemplates[material.properties.material_template].parameters;
                       index as i" [name]="'materialParameter' + i"
                       [label]="parameter.name" appValidate="string" required
                       [(ngModel)]="material.properties[parameter.name]" #parameterInput="ngModel">
          <ng-template rbFormValidationMessage="failure">{{parameterInput.errors.failure}}</ng-template>
          <ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
        </rb-form-input>
      </div>

      <div>
        <rb-form-select name="type" label="type" required [(ngModel)]="baseSample.type" ngModel
                        *ngIf="baseSample.type !== undefined"
                        title="material status of the sample">
          <option value="as-delivered/raw">as-delivered/raw</option>
          <option value="processed">processed</option>
          <ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
        </rb-form-select>
        <rb-form-input name="color" label="color" appValidate="string" [(ngModel)]="baseSample.color"
                       *ngIf="baseSample.color !== undefined" #colorInput="ngModel" title="sample color, eg. black">
          <ng-template rbFormValidationMessage="failure">{{colorInput.errors.failure}}</ng-template>
          <ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
        </rb-form-input>
        <rb-form-input name="batch" label="batch" appValidate="string" [(ngModel)]="baseSample.batch"
                       #batchInput="ngModel" *ngIf="baseSample.batch !== undefined"
                       title="batch number the sample was from, eg. 2264486614">
          <ng-template rbFormValidationMessage="failure">{{batchInput.errors.failure}}</ng-template>
        </rb-form-input>
      </div>
    </div>

    <div class="notes" *ngIf="baseSample.notes !== undefined">
      <rb-form-input name="comment" label="comment" appValidate="stringLength" [appValidateArgs]="[512]"
                     [(ngModel)]="baseSample.notes.comment" #commentInput="ngModel"
                     title="general remarks that cannot be expressed in additional properties, eg. stabilized">
        <ng-template rbFormValidationMessage="failure">{{commentInput.errors.failure}}</ng-template>
      </rb-form-input>
      <h5>Sample references</h5>
      <div *ngFor="let reference of sampleReferences; index as i" class="two-col" [@inOut]>
        <div>
          <rb-form-input [name]="'sr-id' + i" label="sample number"
                         [rbFormInputAutocomplete]="sampleReferenceListBind()"
                         [rbDebounceTime]="300" appValidate="stringOf"
                         [appValidateArgs]="[sampleReferenceAutocomplete[i]]"
                         (ngModelChange)="checkSampleReference($event, i)" [ngModel]="reference[0]" ngModel
                         title="sample number of the referenced sample, eg. An31">
            <ng-template rbFormValidationMessage="failure">Unknown sample number</ng-template>
          </rb-form-input>
        </div>
        <rb-form-input [name]="'sr-relation' + i" label="relation" appValidate="string" [required]="reference[0] !== ''"
                       [(ngModel)]="reference[1]" title="description how the samples are connected, eg. belongs to">
          <ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
        </rb-form-input>
      </div>
      <h5>Additional properties</h5>
      <rb-array-input [(ngModel)]="customFields" name="customFields" [pushTemplate]="['', '']" pushPath="0"
                      class="two-col" [@inOut]>
        <ng-container *rbArrayInputItem="let item">
          <div>
            <rb-form-input [name]="'cf-key' + item.i" label="key" [rbArrayInputListener]="'cf-key'" [index]="item.i"
                           [rbFormInputAutocomplete]="autocomplete.bind(this, availableCustomFields)"
                           [rbDebounceTime]="0"
                           [rbInitialOpen]="true" appValidate="unique" [appValidateArgs]="[uniqueCfValues(item.i)]"
                           [(ngModel)]="item.value[0]" #keyInput="ngModel" title="name of additional property, eg. vwz">
              <ng-template rbFormValidationMessage="failure">{{keyInput.errors.failure}}</ng-template>
            </rb-form-input>
          </div>
          <rb-form-input [name]="'cf-value' + item.i" label="value" appValidate="string"
                         [required]="item.value[0] !== ''"
                         [(ngModel)]="item.value[1]" title="value of additional property, eg. 0 min">
            <ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
          </rb-form-input>
        </ng-container>
      </rb-array-input>
    </div>

    <div *ngIf="samples.length; else generateSamples" class="space-below">
      <rb-icon-button icon="save" mode="primary" type="submit" (click)="saveSample()"
                      [disabled]="!sampleForm.form.valid">
        Save sample
      </rb-icon-button>
      <rb-icon-button class="delete-sample" icon="delete" mode="danger" *ngIf="samples.length > 1"
                      (click)="deleteConfirm(modalDeleteConfirm)">
        Delete samples
      </rb-icon-button>
    </div>
    <ng-template #generateSamples>
      <rb-form-input type="number" name="sample-count" label="number of samples" pattern="^\d+?$" required
                     rbNumberConverter rbMin="1" [(ngModel)]="sampleCount" class="sample-count"
                     title="number of samples to create with this base information">
        <ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
        <ng-template rbFormValidationMessage="rbMin">Must be at least 1</ng-template>
      </rb-form-input>
      <button class="rb-btn rb-primary space-below" type="submit" (click)="saveSample()"
              [disabled]="!sampleForm.form.valid">
        Generate sample{{sampleCount > 1 ? 's' : ''}}
      </button>
    </ng-template>
  </form>

<!--BASE SUMMARY-->

  <div *ngIf="view.baseSum">
    <h3 *ngIf="mode === 'new'">Successfully added samples:</h3>
    <span class="rb-ic rb-ic-edit clickable" (click)="checkFormAfterInit = view.base = true; view.baseSum = false">
    </span>
    <rb-table id="response-data">
      <tr><td>Material</td><td>{{material.name}}</td></tr>
      <tr><td>Type</td><td>{{baseSample.type}}</td></tr>
      <tr><td>color</td><td>{{baseSample.color}}</td></tr>
      <tr><td>Batch</td><td>{{baseSample.batch}}</td></tr>
      <tr><td>Comment</td><td>{{baseSample.notes | exists:'comment'}}</td></tr>
      <tr *ngFor="let reference of sampleReferences.slice(0, -1)">
        <td>Sample reference</td><td>{{reference[0]}} - {{reference[1]}}</td>
      </tr>
      <tr *ngFor="let field of customFields"><td>{{field[0]}}</td><td>{{field[1]}}</td></tr>
    </rb-table>
  </div>

<!--CM-->

  <div *ngIf="view.cm">
    <form #cmForm="ngForm" [ngClass]="{'cm-form': samples.length > 1}">
      <rb-tab-panel (tabChanged)="cmSampleIndex = $event" class="space-below" *ngIf="samples.length > 1">
        <ng-container *ngFor="let sample of samples; index as i">
          <div *rbTabPanelItem="sample.number; id: i"></div>
        </ng-container>
      </rb-tab-panel>
      <div *ngFor="let sample of samples; index as gIndex"
           [ngStyle]="{display: gIndex == cmSampleIndex || gIndex == cmSampleIndex  + 1 ? 'initial' : 'none'}">
        <h4 *ngIf="samples.length > 1">{{sample.number}}</h4>
        <div class="conditions shaded-container space-below">
          <h5>
            Condition
            <button class="rb-btn rb-secondary condition-set" type="button" (click)="toggleCondition(sample)">
              {{sample.condition.condition_template ? 'Do not set condition' : 'Set condition'}}
            </button>
          </h5>
          <div *ngIf="sample.condition.condition_template" [@inOut]>
            <rb-form-select [name]="'conditionSelect-' + gIndex" label="Condition"
                            [(ngModel)]="sample.condition.condition_template"
                            (ngModelChange)="reValidate()">
              <option [value]="sample.condition.condition_template">
                {{d.id.conditionTemplates[sample.condition.condition_template].name}} - current
              </option>
              <option *ngFor="let c of d.latest.conditionTemplates" [value]="c._id">{{c.name}}</option>
            </rb-form-select>

            <ng-container *ngFor="let parameter of
                          d.id.conditionTemplates[sample.condition.condition_template].parameters; index as i"
                          [ngSwitch]="(parameter.range.values ? 1 : 0)">
              <rb-form-select *ngSwitchCase="1"
                              [name]="'conditionParameter-' + gIndex + '-' + i"
                              [label]="parameter.name" [(ngModel)]="sample.condition[parameter.name]" ngModel>
                <option *ngFor="let value of parameter.range.values" [value]="value">{{value}}</option>
                <ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
              </rb-form-select>
              <rb-form-input *ngSwitchDefault (focus)="checkFormAfterInit = true"
                             [name]="'conditionParameter-' + gIndex + '-' + i"
                             [label]="parameter.name" appValidate="string" required
                             [(ngModel)]="sample.condition[parameter.name]" #parameterInput="ngModel">
                <ng-template rbFormValidationMessage="failure">{{parameterInput.errors.failure}}</ng-template>
                <ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
              </rb-form-input>
            </ng-container>
          </div>
        </div>

        <div class="measurements shaded-container space-below">
          <h5>
            Measurements
            <rb-icon-button icon="undo" mode="secondary" *ngIf="measurementRestoreData.length"
                            class="restore-measurements" (click)="restoreMeasurements()">
              Restore measurements
            </rb-icon-button>
          </h5>
          <div *ngFor="let measurement of sample.measurements; index as mIndex" [@inOut]  class="space-below">
            <rb-form-select [name]="'measurementTemplateSelect-' + gIndex + '-' + mIndex" label="Template"
                            [(ngModel)]="measurement.measurement_template"
                            (ngModelChange)="clearMeasurement(gIndex, mIndex)">
              <option [value]="sample.condition.condition_template">
                {{d.id.measurementTemplates[measurement.measurement_template].name}} - old
              </option>
              <option *ngFor="let m of d.latest.measurementTemplates" [value]="m._id">{{m.name}}</option>
            </rb-form-select>
            <div *ngFor="let parameter of d.id.measurementTemplates[measurement.measurement_template].parameters;
                 index as pIndex">
              <ng-container [ngSwitch]="(parameter.range.type ? 1 : 0) + (parameter.range.values ? 2 : 0)">
                <rb-form-file *ngSwitchCase="1"
                              [name]="'measurementParameter-' + gIndex + '-' + mIndex + '-' + pIndex"
                              [label]="parameter.name" maxSize="10000000" multiple
                              [required]="measurement.values[parameter.name] &&
                              !measurement.values[parameter.name].length"
                              (ngModelChange)="fileToArray($event, gIndex, mIndex, parameter.name)"
                              placeholder="Select file or drag and drop" dragDrop ngModel>
                  <ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
                </rb-form-file>
                <rb-form-select *ngSwitchCase="2"
                                [name]="'measurementParameter-' + gIndex + '-' + mIndex + '-' + pIndex"
                                [label]="parameter.name" [(ngModel)]="measurement.values[parameter.name]" ngModel>
                  <option *ngFor="let device of d.d.user.devices" [value]="device">{{device}}</option>
                  <ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
                </rb-form-select>
                <rb-form-input *ngSwitchDefault
                               [name]="'measurementParameter-' + gIndex + '-' + mIndex + '-' + pIndex"
                               [label]="parameter.name" appValidate="string"
                               [(ngModel)]="measurement.values[parameter.name]" #parameterInput="ngModel">
                  <ng-template rbFormValidationMessage="failure">{{parameterInput.errors.failure}}</ng-template>
                  <ng-template rbFormValidationMessage="required">Cannot be empty</ng-template>
                </rb-form-input>
              </ng-container>
              <canvas baseChart *ngIf="parameter.range.type && charts[gIndex][mIndex][0].data.length > 0"
                      class="dpt-chart"
                      [@inOut]
                      [datasets]="charts[gIndex][mIndex]"
                      [labels]="[]"
                      [options]="chartOptions"
                      [legend]="false"
                      chartType="scatter">
              </canvas>
            </div>
            <rb-icon-button icon="delete" mode="danger" (click)="removeMeasurement(gIndex, mIndex)">
              Delete measurement
            </rb-icon-button>
          </div>
          <div>
            <rb-icon-button icon="add" mode="secondary" (click)="addMeasurement(gIndex)">
              New measurement
            </rb-icon-button>
          </div>
        </div>
      </div>
      <div class="buttons">
        <rb-icon-button icon="summary" mode="primary" type="submit" (click)="view.cm = false; view.cmSum = true"
                        [disabled]="!cmForm.form.valid">
          Summary
        </rb-icon-button>
        <rb-icon-button class="delete-sample" icon="delete" mode="danger" *ngIf="samples.length === 1"
                        (click)="deleteConfirm(modalDeleteConfirm)">
          Delete sample
        </rb-icon-button>
      </div>
    </form>
  </div>

<!--CM SUMMARY-->

  <div *ngIf="view.cmSum">
    <span class="rb-ic rb-ic-edit clickable" (click)="checkFormAfterInit = view.cm = true; view.cmSum = false">
    </span>
    <rb-table>
      <ng-container *ngFor="let sample of samples; index as gIndex">
        <tr><th>{{sample.number}}</th><th></th></tr>
        <tr *ngFor="let parameter of (d.id.conditionTemplates[sample.condition.condition_template] || {parameters: []})
            .parameters">
          <td>{{parameter.name}}</td><td>{{sample.condition[parameter.name]}}</td>
        </tr>
        <ng-container *ngFor="let measurement of sample.measurements">
          <tr *ngFor="let parameter of d.id.measurementTemplates[measurement.measurement_template].parameters">
            <td>{{parameter.name}}</td><td>{{measurement.values[parameter.name]}}</td>
          </tr>
        </ng-container>
      </ng-container>
    </rb-table>
    <rb-icon-button icon="save" mode="primary" type="submit" (click)="cmSave()">
      Save sample{{samples.length > 1 ? 's' : ''}}
    </rb-icon-button>
  </div>
</ng-template>

<ng-template #modalDeleteConfirm>
  <rb-alert alertTitle="Are you sure?" type="danger" [okBtnLabel]="'Delete sample' + (samples.length > 1 ? 's' : '')"
            cancelBtnLabel="Cancel">
    Do you really want to delete {{(samples.length > 1 ? 'samples ' : 'sample ') + sampleNames()}}?
  </rb-alert>
</ng-template>

