import { Component, OnInit } 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-current',
  templateUrl: './current.page.html',
  styleUrls: ['./current.page.scss'],
})
export class CurrentPage implements OnInit {

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

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

  ngOnInit() {
    this.getpostulations();
  }

  refresh(event) {
    this.ichambaService.getPostulation().subscribe(
      data => {
        this.postulations = data;
        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'}));
        }
        event.target.complete();
      }, error => {
        this.alertService.presentToast("Por favor contacte a soporte técnico, Estatus:" + error['status']);
        event.target.complete();
      });
  }

  getpostulations() {
    this.ichambaService.getPostulation().subscribe(
      data => {
        this.postulations = data;
        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'}));
        }
      }, error => {
        this.alertService.presentToast("Por favor contacte a soporte técnico, Estatus:" + error['status']);
      });
  }

  addpostulation(id: String) {
    this.ichambaService.setPostulation(id).subscribe(
      data => {
        this.getpostulations();
        this.alertService.presentToast(data['message']);
      }, error => {
        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 });
  }

}
