import { Component, OnInit, Input } from '@angular/core';
import { Router } from '@angular/router';
import {MatDialog} from '@angular/material/dialog';

import { SchoolService } from '../../../services/school.service';
import { LoginService } from '../../../services/login.service';

import { SchoolData } from '../../../structures/school-data';

import { emptySchoolDataFactory } from '../../../empty-objects/empty-school-data';

import { SchoolPrivacyAgreementDialogComponent } from '../../../school/components/school-privacy-agreement-dialog/school-privacy-agreement-dialog.component';

import * as Globals from '../../../globals';

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

  @Input() targetAfterSubmit: string = Globals.pages.allSchools.path;

  @Input() schoolData: SchoolData = emptySchoolDataFactory();
  model: SchoolData = emptySchoolDataFactory();

  schoolDataSavingStatus: number = Globals.savingStatus.none;

  constructor(private loginService: LoginService, private schoolService: SchoolService, private router: Router, public dialog: MatDialog) { 
    // indikator ukladani
    this.schoolService.saveStatusReset();
    this.schoolService.schoolSaveStatus$.subscribe( val => this.schoolDataSavingStatus = val );
    this.loginService.saveStatusReset();
    this.loginService.schoolSaveStatus$.subscribe( val => this.schoolDataSavingStatus = val );
  }

  ngOnInit(): void {
    this.model = JSON.parse(JSON.stringify(this.schoolData));

    var userData = this.loginService.getActualUserData();
    if(userData?.instructor != null) {
      this.targetAfterSubmit = Globals.pages.schoolDetail.path;
    }
    if(Globals.pages.schoolDetail.path == this.targetAfterSubmit) {
      this.targetAfterSubmit = Globals.pages.schoolDetail.path + '/' + this.schoolData.ID;
    }
  }

  async saveData(): Promise<void> {
    var userData = this.loginService.getActualUserData();
    if(userData?.logged == 'school') {
      var data = await this.loginService.saveSchoolData(this.model);
    } else {
      var data = await this.schoolService.saveSchoolData(this.model);
    }
    if(data != null) {
      this.router.navigate([this.targetAfterSubmit]);
    } else {
      //this.router.navigate([this.targetAfterSubmit]);
    }
  }

  openPrivacyDialog() {
    const dialogRef = this.dialog.open(SchoolPrivacyAgreementDialogComponent);
  }

}
