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 { JobListing } from 'app/models/JobListing';
import { Authentication } from 'app/services/Authentication';
import { JobFilter } from 'app/models/JobFilter';

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

  public currentFilter: JobFilter;
  public JobListingPage: JobListing[] = [];
  public ErrorMsg: string = "";

  public Page: number = 1;

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

  ngOnInit(){
    this.http.get<JobListing[]>("api/joblisting?PageQuantity=" + this.currentFilter.JobsPerPage + "&Page=" + this.currentFilter.CurrentPage).subscribe({
      next: data => {
        this.JobListingPage = data;
      },
      error: err => {
        this.ErrorMsg = err.error;
      }
    });
  }

  checkUpdate(){
    if ( this.currentFilter.PostalCode === "" || this.currentFilter.CountryCode === "" ){
      this.currentFilter.Distance = null;
    }
  }

  reloadFilters(){
    var queryBuilder = "api/joblisting?PageQuantity=" + this.currentFilter.JobsPerPage + "&Page=" + this.currentFilter.CurrentPage;

    if ( this.currentFilter.PostalCode === "" || this.currentFilter.CountryCode === "" ){
      this.currentFilter.Distance = null;
    }

    if (this.currentFilter.PostalCode != null){
      queryBuilder += "&PC=" + this.currentFilter.PostalCode;
    }
    if (this.currentFilter.CountryCode != null){
      queryBuilder += "&CC=" + this.currentFilter.CountryCode;
    }
    if (this.currentFilter.Distance != null){
      queryBuilder += "&D=" + this.currentFilter.Distance;
    }
    if (this.currentFilter.JobType != null){
      queryBuilder += "&JT=" + this.currentFilter.JobType;
    }
    if (this.currentFilter.Remote != null){
      queryBuilder += "&R=" + this.currentFilter.Remote;
    }
    if (this.currentFilter.SalaryMin != null){
      queryBuilder += "&SMI=" + this.currentFilter.SalaryMin;
    }
    if (this.currentFilter.SalaryMax != null){
      queryBuilder += "&SMA=" + this.currentFilter.SalaryMax;
    }

    this.http.get<JobListing[]>(queryBuilder).subscribe({
      next: data => {
        this.JobListingPage = data;
      },
      error: err => {
        this.ErrorMsg = err.error;
      }
    });
  }

}