import { Component, NgZone } from '@angular/core';
import { IonicPage, NavController, NavParams, Platform, LoadingController, AlertController, MenuController } from 'ionic-angular';
import { dataService } from "../../providers/common.service";
import { Myservice } from "../../providers/myservice";
import { Storage } from "@ionic/storage";
import { user } from "../../models/mymodel";
import * as firebase from 'firebase';
import { TranslateService } from "@ngx-translate/core";

declare var google;
@IonicPage()
@Component({
  selector: 'page-ridedetail',
  templateUrl: 'ridedetail.html',
})
export class RidedetailPage {
  book: any;
  geocoder: any;
  loc = { from: '', to: '', fromAd: '', toAd: '' }
  local: user
  public unregisterBackButtonAction: any;
  count: number = 0;
  loader: any;
  driver: any;
  bkid: any;
  drivers = []
  temp: boolean = false;
  lang: string = 'en';
  baseUrl :string = this.myservice.base_url

  constructor(public navCtrl: NavController, public navParams: NavParams, private data: dataService, private zone: NgZone, private myservice: Myservice, private storage: Storage, public platform: Platform, public loadingCtrl: LoadingController, private alertCtrl: AlertController, private translate: TranslateService, private menu:MenuController) {
  }

  ionViewDidEnter() {
    this.menu.swipeEnable(false)
    this.storage.get('lang').then(lang => {
      if (lang != null) {
        this.translate.use(lang)
        this.lang = lang;
      }
      else {
        this.translate.use('en')
      }
    })

    this.initializeBackButtonCustomHandler();
    
    this.storage.get('user_data').then(data => {
      if (data) {
        this.local = data
        this.book = this.data.getbookingData()
        console.log(this.book)

        this.translate.get(['ride.Searching for driver']).subscribe(value => {
          this.loader = this.loadingCtrl.create({
            content: value['ride.Searching for driver']
          });
        })
        this.loader.present();

        this.findDrivers()

        this.geocoder = new google.maps.Geocoder();
        for (let i = 0; i < 2; i++) {
          if (i == 0) {
            var lat = this.book.pickLat
            var lng = this.book.pickLng
          }
          else {
            var lat = this.book.dropLat
            var lng = this.book.dropLng
          }
          var latlng = new google.maps.LatLng(lat, lng);
          var This = this;
          This.geocoder.geocode({ 'latLng': latlng }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
              if (results[0]) {
                // console.log(results)
                if (i == 0) {
                  var temp = This.book.pickArea.split(',')
                  // This.loc.from = results[0].address_components[0].short_name
                  This.loc.from = temp[0]
                  This.loc.fromAd = results[0].formatted_address
                }
                else {
                  var temp = This.book.dropArea.split(',')
                  This.loc.to = temp[0]
                  // This.loc.to = results[0].address_components[0].short_name
                  This.loc.toAd = results[0].formatted_address
                  This.zone.run(() => { });
                }
              }
            }
            else {
              console.log("Geocoder failed due to: " + status);
            }
          });
        }
      }
    })
  }

  findDrivers() {
    var This = this
    firebase.database().ref().child('/drivers/').orderByChild("status").equalTo('online').once("value", function (snapshot) {
      var res_arr = []
      res_arr = (<any>Object).entries(snapshot.val()).map(e => Object.assign(e[1], { key: e[0] }));
      console.log(res_arr)
      This.drivers = [];
      for (let i = 0; i < res_arr.length; i++) {
        var mypos = new google.maps.LatLng(This.book.pickLat, This.book.pickLng);
        let driverLoc = new google.maps.LatLng(res_arr[i].lat, res_arr[i].lng)
        if (google.maps.geometry.spherical.computeDistanceBetween(driverLoc, mypos) < 5000) {
          This.drivers.push(res_arr[i].id)
        }
        if (i == res_arr.length - 1) {
          if (This.drivers.length == 0) {
            This.loader.dismissAll();
            This.translate.get(['ride.No drivers found']).subscribe(value => {
              This.myservice.show_alert('', value['ride.No drivers found'])
            })
          }
          else if (This.temp == false) {
            var bdata = { 'book_date': This.book.date, 'drop_area': This.book.dropArea, 'pickup_area': This.book.pickArea, 'taxi_type': This.book.carDetails.car_type, 'amount': '', 'km': '', 'promocode': This.book.promocode, 'token': This.local.token, 'userid': This.local.id, 'type': 'now', 'drivers': [], 'discount': This.book.discount ? This.book.discount : 0, 'pickup_latlng': This.book.pickLat + ',' + This.book.pickLng, 'drop_latlng': This.book.dropLat + ',' + This.book.dropLng }

            bdata.drivers = This.drivers;

            console.log(bdata)

            This.myservice.load_post(bdata, 'book_cab').subscribe(response => {
              if (response.status == 'success') {
                This.bkid = response.data
                This.book.bookingId = This.bkid
                This.data.setbookingData(This.book);
                This.checkResp();
                This.temp = true
              }
              else {
                This.translate.get(['ride.' + response.message]).subscribe(value => {
                  This.myservice.show_alert('', value['ride.' + response.message])
                })
                This.navCtrl.pop()
              }
            })

          }
        }
      }
    });
  }

  showAlert() {
    this.translate.get(['ride.No drivers are available', 'ride.Please search again', 'ride.Cancel', 'ride.Search','ride.Searching for driver']).subscribe(value => {

      let alert = this.alertCtrl.create({
        title: value['ride.No drivers are available'],
        message: value['ride.Please search again'],
      buttons: [
        {
          text: value['ride.Cancel'],
          role: 'cancel',
          handler: () => { }
        },
        {
          text: value['ride.Search'],
          handler: () => {
            
            this.loader = this.loadingCtrl.create({
              content: value['ride.Searching for driver']
            });
            this.loader.present();
            
            this.findDrivers()
            var This = this;
            setTimeout(() => {
              This.myservice.load_post({ taxiType: This.book.carDetails.car_type, driversid: This.drivers, bookid: This.bkid }, 'driverPush').subscribe(data => {
                if (data.status == 'success')
                This.checkResp();
                else{
                  This.translate.get(['ride.' + data.message]).subscribe(value => {
                    This.myservice.show_alert('', value['ride.' + data.message])
                  })
                }
              })
            }, 500);
          }
        }
      ]
    });
    alert.present();
  })
  }

  checkResp() {
    var This = this;
    var intrvl = setInterval(function () {
      This.count++;
      This.myservice.load_post({ bkid: This.bkid }, 'checkBookingStatus').subscribe(resp => {
        console.log(resp.data.assigned_for)
        if (resp.data.assigned_for) {
          This.driver = resp.data
          clearInterval(intrvl)
          This.loader.dismissAll();
        }
      })
      if (This.count == 12) {
        clearInterval(intrvl)
        This.loader.dismissAll();
        This.showAlert();
      }
    }, 5000)
  }

  public initializeBackButtonCustomHandler(): void {
    this.unregisterBackButtonAction = this.platform.registerBackButtonAction(() => {
      // this.customHandleBackButton();
    }, 10);
  }

  ionViewWillLeave() {
    this.unregisterBackButtonAction && this.unregisterBackButtonAction();
    this.menu.swipeEnable(true)
  }

  track() {
    this.data.setdriverData(this.driver)
    console.log('driv', this.driver)
    this.navCtrl.push('MapPage')
  }
}
