import { Component, ChangeDetectorRef } from '@angular/core';
import { MenuController, NavController } from '@ionic/angular';
import { EventService } from '../../../services/event.service';
import { EnvService } from 'src/app/services/env.service';
import { AuthService } from 'src/app/services/auth.service';
import { IchambaService } from 'src/app/services/ichamba.service';
import { AlertService } from 'src/app/services/alert.service';
import { Browser } from '@capacitor/browser';

@Component({
  selector: 'app-already',
  templateUrl: './already.page.html',
  styleUrls: ['./already.page.scss'],
  standalone: false
})
export class AlreadyPage {

  postulations: any[] = [];
  postulations_dates: any[] = [];
  loading = true;

  constructor(
    private menu: MenuController,
    private navCtrl: NavController,
    private events: EventService,
    private authService: AuthService,
    private alertService: AlertService,
    private ichambaService: IchambaService,
    private env: EnvService,
    private cdr: ChangeDetectorRef,
  ) {
    this.events.subscribe('refreshpostulations', (data) => {
      this.getpostulations();
    });
  }

  ionViewWillEnter() {
    this.loading = true;
    this.getpostulations();
  }

  refresh(event: any) {
    this.ichambaService.getContractedPostulation().subscribe(
      data => {
        this.postulations = data;
        this.postulations_dates = [];
        for (var i of this.postulations) {
          this.postulations_dates.push(new Date((new Date(i.date).toLocaleString('en-US') + ' UTC').replace(',', '')).toLocaleDateString('es-US', { weekday: 'long', year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: 'numeric', timeZoneName: 'long' }));
        }
        this.cdr.detectChanges();
        event.target.complete();
      }, error => {
        this.alertService.presentToast("Por favor contacte a soporte técnico, Estatus:" + error['status']);
        event.target.complete();
      });
  }

  getpostulations() {
    this.ichambaService.getContractedPostulation().subscribe(
      data => {
        this.postulations = data;
        this.postulations_dates = [];
        for (var i of this.postulations) {
          this.postulations_dates.push(new Date((new Date(i.date).toLocaleString('en-US') + ' UTC').replace(',', '')).toLocaleDateString('es-US', { weekday: 'long', year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: 'numeric', timeZoneName: 'long' }));
        }
        this.loading = false;
        this.cdr.detectChanges();
      }, error => {
        this.loading = false;
        this.alertService.presentToast("Por favor contacte a soporte técnico, Estatus:" + error['status']);
      });
  }

  async openMaps(lat: Number, lng: Number) {
    await Browser.open({ url: 'http://maps.google.com/maps?q=' + lat + ',' + lng });
  }

}
