import { NgClass, NgFor } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { api } from '@enums/api.enum';
import { Roots } from '@enums/root.enum';
import { IonicModule, NavController } from '@ionic/angular';
import { AlertService } from '@services/alert.service';
import { HttpRequestService } from '@services/http-request.service';
import { StateManagementService } from '@services/state-management.service';

@Component({
  selector: 'app-post-type',
  templateUrl: './post-type.page.html',
  styleUrls: ['./post-type.page.scss'],
  standalone: true,
  imports: [IonicModule, NgClass, NgFor, FormsModule]
})
export class PostTypePage implements OnInit {
  postTypeList = [];
  postTypeId: any;
  postType: any;
  type: number;

  constructor(
    private httpRequestService: HttpRequestService,
    private alert: AlertService,
    private navCtrl: NavController,
    private stateManagementService: StateManagementService,
    private router: Router
  ) { }

  ngOnInit() {
    if (this.router.getCurrentNavigation().extras.state?.type) {
      this.type = this.router.getCurrentNavigation().extras.state.type;
    }
    if (this.stateManagementService.postTypeList.length > 0) {
      this.postTypeList = this.stateManagementService.postTypeList;
    } else {
      this.getPostTypes();
    }
    this.postTypeId = this.router.getCurrentNavigation().extras.state.postType || 5;
  }

  getPostTypes() {
    this.httpRequestService.get(api.postTypeList).then((res: any) => {
      this.postTypeList = res.data;
      this.stateManagementService.postTypeList = res.data;
    });
  }

  onTypeChange(type) {
    this.postType = type;
  }

  onSubmit() {
    if (!this.postTypeId) {
      this.alert.showToaster('Please select post type');
      return;
    }
    this.stateManagementService.postTypeSubject.next(this.postType);
    this.navCtrl.navigateForward(Roots.page + '/' + Roots.postFeed);
  }
}
