import { Component, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { Observable, of } from 'rxjs';
import { Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { IJournalEntryModel } from '@fleio-api/billing/model/journal-entry.model';
import { JournalsApiService } from '@fleio-api/billing/journal/journal-api.service';
import { TimeHelper } from '@shared/ui-api/helpers/time-helper';

@Component({
  selector: 'app-server-edit-form',
  templateUrl: './journal-edit-form.component.html',
  styleUrls: ['./journal-edit-form.component.scss']
})
export class JournalEditFormComponent extends DetailsFormBase<IJournalEntryModel> implements OnInit {
  journalEditForm = this.formBuilder.group({
    source: [''],
    destination: [''],
    amount: ['', Validators.required],
    date_added: ['', Validators.required],
    date_added_time: [''],
  });
  timeHelper: TimeHelper;


  constructor(
    private formBuilder: UntypedFormBuilder,
    private journalApiService: JournalsApiService,
    private router: Router,
    private config: ConfigService,
  ) {
    super();
    this.timeHelper = new TimeHelper(config);
  }

  ngOnInit() {
    super.ngOnInit();
    if (this.objectController) {
      this.objectController.actionCallback = () => this.saveJournalEntry();
    }

    this.journalEditForm.patchValue({
      'source': this.object.source_info.name,
      'destination': this.object.destination_info.name,
      'amount': this.object.destination_amount,
      'date_added': new Date(this.object.date_added),
      'date_added_time': new Date(this.object.date_added).toLocaleTimeString(this.config.locale),
    })

    this.journalEditForm.controls.source.disable();
    this.journalEditForm.controls.destination.disable();
  }

  saveJournalEntry(): Observable<IActionResult> {
    const value = this.journalEditForm.value as IJournalEntryModel;

    if (this.timeHelper.processDateFieldTime(value.date_added, this.journalEditForm.controls.date_added_time).error) {
      return of(null);
    }


    this.createOrUpdate(
      this.journalApiService,
      value,
    ).subscribe(() => {
      this.router.navigateByUrl(
        this.config.getPrevUrl('billing/journal')
      ).catch(() => {
      });
    });

    return of(null);
  }
}
