import {Component, OnInit, TemplateRef} from '@angular/core';
import {ChangelogModel} from '../models/changelog.model';
import {ApiService} from '../services/api.service';
import {ModalService} from '@inst-iot/bosch-angular-ui-components';

@Component({
  selector: 'app-changelog',
  templateUrl: './changelog.component.html',
  styleUrls: ['./changelog.component.scss']
})
export class ChangelogComponent implements OnInit {

  timestamp = new Date();  // time from date input
  pageSize = 25;
  changelog: ChangelogModel[] = [];
  modalDetail = 0;        // index of changelog element to show details of

  constructor(
    private api: ApiService,
    private modal: ModalService
  ) { }

  ngOnInit(): void {
    this.loadChangelog();
  }

  loadChangelog(page = 0) {  // load changelog with page no relative to current page
    this.api.get<ChangelogModel[]>(`/changelog/${
      page > 0 ? this.changelog[0]._id :  // use id if no new date was given
      Math.floor(new Date(
        new Date(this.timestamp).getTime() - new Date(this.timestamp).getTimezoneOffset() * 60000  // adjust timezone
      ).getTime() / 1000).toString(16) + '0000000000000000'  // id from time
    }/${page}/${this.pageSize}`, data => {
      this.changelog = data.map(e => new ChangelogModel().deserialize(e));
      if (page) {  // adjust date picker to new first element when user clicked on next page
        this.timestamp = new Date(this.changelog[0].date);
      }
    });
  }

  // show details of a changelog element with reference to needed modal
  showDetails(i: number, modal: TemplateRef<any>) {
    this.modalDetail = i;
    this.modal.open(modal).then(() => {});
  }

}
