import {
  Component,
  effect,
  Input,
  OnInit,
  signal,
  WritableSignal,
} from '@angular/core';
import { PostsService } from '../../../shared/services/posts.service';
import { inject } from '@angular/core';
import { Post } from '../../../shared/interfaces/post';
import { Location } from '@angular/common';
import { PostEditorComponent } from '../../../components/post-editor/post-editor.component';

@Component({
  selector: 'app-update-post',
  imports: [PostEditorComponent],
  templateUrl: './update-post.component.html',
})
export class UpdatePostComponent implements OnInit {
  @Input() id!: string;
  private postsService = inject(PostsService);
  private location = inject(Location);
  post: WritableSignal<Post> = signal({
    id: 0,
    title: '',
    tldr: '',
    content: '',
  });

  ngOnInit(): void {
    const p = this.postsService.getPost(parseInt(this.id))();
    if (p == undefined) {
      this.location.back();
      return;
    }

    this.post.set(p);
  }

  save() {
    this.postsService.updatePost(this.post());
    this.location.back();
  }
}
