import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

import { AppModule } from "../app.module";
import { Machine } from "../machine";
import { MachinesService } from "../machines.service";
import * as $ from 'jquery';
import { Router } from '@angular/router'


declare var Android: any;

@Component({
  selector: 'app-register-equipment',
  templateUrl: './register-equipment.component.html',
  styleUrls: ['./register-equipment.component.scss']
})
export class RegisterEquipmentComponent implements OnInit {

  machineData : Machine = {
    serial_number:'',
    room:'',
    date_last_maintenance: {
			day: '',
			month: '',
			year: ''
		},
    date_next_maintenance: {
			day: '',
			month: '',
			year: ''
		},
    Status:'',
    address:'',
    address_number:'',
    district:'',
    city:'',
    state:'',
		image: new File([''], "nenhuma"),
		imagePath: 'none',
		id: 0,
  }


  constructor(private machineService: MachinesService,
              private _router: Router) {

  }

  ngOnInit() {

  }


  private validateDate(date) {
    var r = true;
    var ListofDays = [31,28,31,30,31,30,31,31,30,31,30,31];

    if ((date.month == '') || (date.day == '') || (date.year == '')) {
      r = false
    }
    if (date.month > 12) {
      r = false
    }

    if (date.month == 2) {
      var ano_bi = false;
      if ( (!(date.year % 4) && date.year % 100) || !(date.year % 400)) {
        ano_bi = true;
      }
      if ( !ano_bi && date.day >= 29 ) {
        r = false;
      }
      if ( ano_bi && date.day > 29 ) {
        r = false;
      }
    }
    else if (date.month <= 12) {
      if (date.day > ListofDays[date.month-1]) {
        r = false;
      }
    }
    return r
  }

  private async valid() {

    var v = true

    for (let i in this.machineData) {
      var x = document.getElementById(i)
      if (this.machineData[i] === '') {
        if (x != null) {x.style.borderColor = "#ff0000"}
        else { console.log(i + " input not found") }
        v = false
      }
      else {
        if (x != null) {x.style.borderColor = "#9d9d9d"}
      }
    }

    if (this.machineData.image.size == 0) {
      x = document.getElementById("image_upload_button")
      if (x != null) {
        x.style.borderColor = "#ff0000"
        x.style.borderStyle = "solid"
      }
      else { console.log("image_upload_button not found") }
      x = document.getElementById("selected_file")
      if (x != null) {x.style.color = "#ff0000"}
      else { console.log("selected_file not found") }
      v = false
    }
    else {
      x = document.getElementById("image_upload_button")
      if (x != null) {
        x.style.borderColor = "#ff0000"
        x.style.borderStyle = "none"
      }
      else { console.log("image_upload_button not found") }
      x = document.getElementById("selected_file")
      if (x != null) {x.style.color = "#4f425b"}
      else { console.log("selected_file not found") }
    }

    if (await this.validateDate(this.machineData.date_last_maintenance)) {
      for (let i in this.machineData.date_last_maintenance) {
        let x = document.getElementById("date_last_maintenance_"+i)
        if (x != null) {x.style.borderColor = "#9d9d9d"}
        else { console.log("date_last_maintenance_"+i+" not found") }
      }
      let x = document.getElementById("date_last_maintenance_error_msg")
      if (x != null) {x.style.display = "none"}
      else { console.log("date_last_maintenance_error_msg not found") }
    }
    else {
      for (let i in this.machineData.date_last_maintenance) {
        let x = document.getElementById("date_last_maintenance_"+i)
        if (x != null) {x.style.borderColor = "#ff0000"}
        else { console.log("date_last_maintenance_"+i+" not found") }
      }
      let x = document.getElementById("date_last_maintenance_error_msg")
      if (x != null) {x.style.display = "block"}
      else { console.log("date_last_maintenance_error_msg not found") }
      v = false
    }

    if (await this.validateDate(this.machineData.date_next_maintenance)) {
      for (let i in this.machineData.date_next_maintenance) {
        let x = document.getElementById("date_next_maintenance_"+i)
        if (x != null) {x.style.borderColor = "#9d9d9d"}
        else { console.log("date_next_maintenance_"+i+" not found") }
      }
      let x = document.getElementById("date_next_maintenance_error_msg")
      if (x != null) {x.style.display = "none"}
      else { console.log("date_next_maintenance_error_msg not found") }
    }
    else {
      for (let i in this.machineData.date_next_maintenance) {
        let x = document.getElementById("date_next_maintenance_"+i)
        if (x != null) {x.style.borderColor = "#ff0000"}
        else { console.log("date_next_maintenance_"+i+" not found") }
      }
      let x = document.getElementById("date_next_maintenance_error_msg")
      if (x != null) {x.style.display = "block"}
      else { console.log("date_next_maintenance_error_msg not found") }
      v = false
    }

    return v;
  }

  async onSubmit() {

		this.machineData.serial_number = this.machineData.serial_number.trim();
		this.machineData.room = this.machineData.room.trim();
		this.machineData.Status = this.machineData.Status.trim();
		this.machineData.address = this.machineData.address.trim();
		this.machineData.address_number = this.machineData.address_number.trim();
		this.machineData.district = this.machineData.district.trim();
		this.machineData.city = this.machineData.city.trim();
		this.machineData.state = this.machineData.state.trim();

		this.machineData.date_last_maintenance.day = this.machineData.date_last_maintenance.day.trim();
		this.machineData.date_last_maintenance.month = this.machineData.date_last_maintenance.month.trim();
		this.machineData.date_last_maintenance.year = this.machineData.date_last_maintenance.year.trim();

		this.machineData.date_next_maintenance.day = this.machineData.date_next_maintenance.day.trim();
		this.machineData.date_next_maintenance.month = this.machineData.date_next_maintenance.month.trim();
		this.machineData.date_next_maintenance.year = this.machineData.date_next_maintenance.year.trim();

    if (await this.valid()) {
		    this.machineService.addMachine(this.machineData)
				    .subscribe(res => {
						  window.alert("Máquina "+res.serial_number+" registrada com sucesso");

					    this.machineData.serial_number = '';
					    this.machineData.room = '';

					    this.machineData.date_last_maintenance.day = '';
					    this.machineData.date_last_maintenance.month = '';
					    this.machineData.date_last_maintenance.year = '';
					    this.machineData.date_next_maintenance.day = '';
					    this.machineData.date_next_maintenance.month = '';
					    this.machineData.date_next_maintenance.year = '';

					    this.machineData.Status = '';
					    this.machineData.address = '';
					    this.machineData.address_number = '';
					    this.machineData.district = '';
					    this.machineData.city = '';
					    this.machineData.state = '';
							this.machineData.image = new File([''], "empty");
							this.machineData.imagePath = '';
							this.machineData.id = 0;

              this._router.navigate(['/edicao-equipamentos'])

					},
					err => console.log("Error: "+err)
				);
    }
    else {
      window.alert("Há campos inválidos")
    }
  }

  scanQRCode () {

    var serial;

    if (typeof (Android) !== 'undefined'){

      Android.scanBarcode();

      while(Android.getSign() < 0){}

      if ((serial = Android.getResult()) != ""){
        alert("Número de Série: " + Android.getResult());
        this.machineData.serial_number = Android.getResult();
      }

    } else {
      alert("Disponivel apenas para dispositivos moveis.")
    }
  }

  onFileSelect (event) {


    if(event.target.files.length > 0) {
			this.machineData.image = event.target.files[0];
		}
  }

  getLocation() {

    if (typeof (Android) !== 'undefined'){
      Android.geolocationPrompt();
    }

		console.log("getting location");

    var self = this;

     if (navigator.geolocation) {

       var optn = {maximumAge:Infinity,
         timeout:27000,
         enableHighAccuracy: true};


       navigator.geolocation.getCurrentPosition((position: Position) => {
         if (position) {
           alert("Preenchendo endereço.");
           console.log("Latitude: " + position.coords.latitude +
             "Longitude: " + position.coords.longitude);


           this.fillData(function(data){

            self.machineData.address =  data.address.road;
            self.machineData.address_number = data.address.house_number;
            self.machineData.district = data.address.suburb;
            self.machineData.city = data.address.city;
            self.machineData.state = data.address.state;

           }, position);

         }
       },
         (error: PositionError) => console.log("error getting location",error.code), optn);

       } else {
         alert("Geolocation is not supported by this browser.");
       }
  }
  fillData(callback, position){
   var url = "https://nominatim.openstreetmap.org/reverse?lat="+position.coords.latitude+"&lon="+position.coords.longitude+"&format=json";
   $.getJSON(url, function(data){
       callback(data);
   });
 }

}