import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AppwriteService } from '../../services/appwrite.service';
import { FormsModule } from '@angular/forms';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',  
  standalone: true,
  imports: [CommonModule, FormsModule],
  templateUrl: './login.component.html',
  styleUrl: './login.component.css'
})
export class LoginComponent {
detailHeight: number = 0;

  email = '';
  password = '';
  sessionId = '';


  constructor(
    private router: Router,
    private appwriteService: AppwriteService
  ) {}


  register() {
    this.router.navigate(['/register']);
  }

  async logout() {
    try {
      await this.appwriteService.accountService.deleteSession(this.sessionId).then((response) => {
        this.sessionId = '';
        this.email = '';
        this.password = '';
        alert('Erfolgreich abgemeldet');
      }).catch((error) => {
        console.error('Fehler beim Abmelden: ' + error.message);
      });
    } catch (err: any) {
      console.error('Logout fehlgeschlagen: ' + err.message);
    }
  }
  async login() {
    try {
      await this.appwriteService.accountService.createEmailPasswordSession(
        this.email,
        this.password,
      ).then((response) => {
        this.sessionId = response.$id;
        this.email = '';
        this.password = '';
        //this.router.navigate(['/input']);
      }).catch((error) => { 
        console.error('Fehler beim Anmelden: ' + error.message);
        alert('Fehler beim Anmelden: ' + error.message);  
      });
    } catch (err: any) {
      console.error('Anmeldung fehlgeschlagen: ' + err.message);
    }
  }

}
