import {Component, EventEmitter, Input, OnDestroy, OnInit, OnChanges, Output} from '@angular/core';
import {Router} from '@angular/router';
import {DatePipe} from '@angular/common';

import { WeatherService } from 'src/app/services/weather.service';
import { Subscription } from 'rxjs';
import {first} from 'rxjs/operators';

@Component({
  selector: 'app-weather-card',
  templateUrl: './weather-card.component.html',
  styleUrls: ['./weather-card.component.scss']
})

export class WeatherCardComponent implements OnInit, OnChanges {
  @Input() city: string;
  listData: any;
  citesWeather: Object;
  darkMode: boolean;
  sub1: Subscription;
  state: string;
  temp: number;
  maxTemp: number;
  minTemp: number;
  errorMessage: string;
  cityName: string;
  cityAdded = false;
  icon: string;
  icon_exists: boolean;
  pipe = new DatePipe('es-ES')
  newDate = Date.now();
  currentDate = this.pipe.transform(this.newDate, 'fullDate')
  errorWeather: boolean = false;
  constructor(public weather: WeatherService, public router: Router) {

  }

  ngOnInit() {
    if (this.city == undefined){
      this.city = "San%20Salvador,+SV";
    }
    else {
      this.city = this.city + ",+SV";
    }
    this.getWeather(this.city);
  }

  ngOnChanges() {
    if (this.city == undefined){
      this.city = "San%20Salvador,+SV";
    }
    else {
      this.city = this.city + ",+SV";
    }
    this.getWeather(this.city);
  }

  getWeather(city:string){
    this.weather.getWeather(city)
    .pipe(first())
    .subscribe((payload) => {
      this.errorWeather = false;
      this.cityName = payload.name
      this.state = payload.weather[0].description;
      this.temp = Math.ceil(payload.main.temp);
      this.icon_exists = true;
      this.icon = payload.weather[0].icon;
    }, (err) => {
      this.errorWeather = true;
      this.errorMessage = err.error.message;
      if (this.errorMessage == "city not found"){
        this.errorMessage = "Datos del clima para el municipio de la planta no disponible.";
      }
    });

  }

}
