import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { Router, ActivatedRoute, RouterModule } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';
import { Authentication } from 'app/services/Authentication';
import { Company } from 'app/models/Company';
import { JobListing } from 'app/models/JobListing';
import { Employee } from 'app/models/Employee';

@Component({
  selector: 'main-company',
  templateUrl: './company.component.html',
  styleUrls: [ './company.component.css' ],
  imports: [ FormsModule, CommonModule, RouterModule ]
})
export class CompanyComponent {
  public ErrorMsg: string = "";

  public Employers: Employee[] = [];

  public Comp: Company | null = null;
  public CompEmployees: Employee[] = [];
  public Desc: string[] = [];

  public List: JobListing[] = [];

  constructor( private http: HttpClient, private router: Router, private route: ActivatedRoute, private title: Title, public auth: Authentication  ) {
    this.title.setTitle("Companies | BoredCareers");
    if (!auth.isLoggedIn){
      router.navigate(["/"]);
    }
  };

  ngOnInit(){
    this.http.get<Employee[]>("api/employee/").subscribe({
      next: data => {
        this.Employers = data;
        if (data[0] != null){
          if (data[0].company.id !== null){
            this.changeSelectedCompany(data[0].company.id);
          }
        }
      },
      error: err => {
        this.ErrorMsg = err.error;
      }
    });
  }

  changeSelectedCompany(companyID: number){
    this.http.get<Company>("api/company?CompanyID=" + companyID).subscribe({
      next: data => {
        this.Comp = data;
        this.Desc = data.description.split("\n");
      },
      error: err => {
        this.ErrorMsg = err.error;
      }
    });

    this.http.get<JobListing[]>("api/joblisting/company?CompanyID=" + companyID).subscribe({
      next: data => {
        this.List = data;
      },
      error: err => {
        this.ErrorMsg = err.error;
      }
    });

    this.http.get<Employee[]>("api/employee/" + companyID).subscribe({
      next: data => {
        this.CompEmployees = data;
      },
      error: err => {
        this.ErrorMsg = err.error;
      }
    });
  }

  RemoveJobListing( JobListingID: number ){
    this.http.delete("api/joblisting?JobListingID=" + JobListingID).subscribe({
      next: data => {
        window.location.reload();
      },
      error: err => {
        this.ErrorMsg = err.error;
      }
    });
  }

}