import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Note } from '../models/note.model';
import { NoteService } from '../services/note.service';

@Component({
  selector: 'app-note-form',
  templateUrl: './note-form.component.html',
  styleUrls: ['./note-form.component.scss']
})
export class NoteFormComponent implements OnInit {
  note: Note = { title: '', content: '' };
  isEditMode = false;

  constructor(
    private noteService: NoteService,
    private route: ActivatedRoute,
    private router: Router
  ) { }

  ngOnInit(): void {
    this.route.paramMap.subscribe(params => {
      const id = params.get('id');
      if (id) {
        this.isEditMode = true;
        this.noteService.getNote(+id).subscribe(note => {
          this.note = note;
        });
      }
    });
  }

  saveNote(): void {
    if (this.isEditMode && this.note.id) {
      this.noteService.updateNote(this.note.id, this.note).subscribe(() => {
        this.router.navigate(['/notes']);
      });
    } else {
      this.noteService.createNote(this.note).subscribe(() => {
        this.router.navigate(['/notes']);
      });
    }
  }
}