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 { JobListing } from 'app/models/JobListing';
import { Company } from 'app/models/Company';
import { Resume } from 'app/models/Resume';
import { Application } from 'app/models/Application';

@Component({
  selector: 'main-jobs-viewer',
  templateUrl: './jobviewer.component.html',
  styleUrls: [ './jobviewer.component.css' ],
  imports: [ FormsModule, CommonModule, RouterModule ]
})
export class JobViewerComponent {

  public selectedJob: JobListing | null = null;
  public myResumes: Resume[] = [];
  public jobsCompany: Company | null = null;
  public ErrorMsg: string = "";

  JobListingID: number = -1;

  constructor( private http: HttpClient, private router: Router, private route: ActivatedRoute, private title: Title, public auth: Authentication ) {
    this.title.setTitle("Jobs - Viewer | BoredCareers");
  };

  ngOnInit(){
    this.route.queryParams.subscribe(params => {
      const JobID = params['JobID'];
      if (JobID) {
        this.JobListingID = JobID;
        this.http.get<JobListing>( "api/joblisting/" + JobID ).subscribe({
          next: data => {
            this.selectedJob = data;
            this.http.get<Company>("api/company?CompanyID=" + this.selectedJob.companyID).subscribe({
              next: data => {
                this.jobsCompany = data;
              },
              error: err => {
                this.ErrorMsg = err.ErrorMsg;
              }
            })
          },
          error: err => {
            this.ErrorMsg = err.error;
          }
        })
      }else{
        this.router.navigate(["/"]);
      }
      if (this.selectedJob != null){
        
      }
    });

    this.http.get<Resume[]>("api/resume").subscribe({
      next: data => {
        this.myResumes = data;
      },
      error: err => {
        console.log("Error fetching resumes: " + err.error);
      }
    });
  }

  applyWithResume(resume: Resume) {
      var application = new Application;

      if (this.auth.loggedInUser.id != null){
        application.accountID = this.auth.loggedInUser.id;
      }

      if (resume.id != null){
        application.resumeID = resume.id;
      }

      application.jobListingID = this.JobListingID;
      application.hasBeenViewed = false;
      application.responseEmail = resume.email;

      this.http.post("api/application", application).subscribe({
      next: data => {
        this.router.navigate(["/"]);
      },
      error: err => {
        this.ErrorMsg = err.error;
      }
    });
      
  }

}