import { Component, OnInit, ViewChild, ElementRef, NgZone } from '@angular/core';
import { Location } from '@angular/common';
import { trigger, transition, animate, style } from '@angular/animations';
import { MapsAPILoader, MouseEvent } from '@agm/core';
import { Router, ActivatedRoute } from '@angular/router';
import { MenuController } from '@ionic/angular';
import { CenterService } from './../../config/center.service';
import { ShoppersService } from './../../config/shopper.service';
import { CategoriesService } from './../../config/category.service';
import { ServiceService } from './../../config/service.service';
import { SubjectService } from './../../config/subject.service';
import { AddressService } from './../../config/address.service';
import { SearchService } from './../../config/search.service';
import { ProductsService } from './../../config/products.service';

import { from } from 'rxjs';
import { ModalController } from '@ionic/angular';
import { SearchmodalPage } from '../searchmodal/searchmodal.page';
import { AuthService } from 'src/config/auth.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.page.html',
  styleUrls: ['./home.page.scss'],
  animations: [
    trigger('slideInOut', [
      transition(':enter', [
        style({ transform: 'translateY(100%)' }),
        animate('200ms ease-in', style({ transform: 'translateY(0%)' }))
      ]),
      transition(':leave', [
        animate('200ms ease-out', style({ transform: 'translateY(100%)' }))
      ])
    ])
  ]
})
export class HomePage implements OnInit {
  isShow = true;
  searchShow = false;
  public lat = 51.678418;
  public lng = 7.809007;
  loader: boolean;
  address: any;
  custId: any;
  private geoCoder;
  subscription: any;
  slideOpts = {
    slidesPerView: 1.5
  };
  @ViewChild('building', { static: false })
  public searchElementRef: ElementRef;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private location: Location,
    public menuCtrl: MenuController,
    public centerService: CenterService,
    public shopperService: ShoppersService,
    public categoriesService: CategoriesService,
    public addressService: AddressService,
    public service: ServiceService,
    public modalController: ModalController,
    private mapsAPILoader: MapsAPILoader,
    private searchService: SearchService,
    private productsService: ProductsService,
    private subjectService: SubjectService,
    private authService: AuthService,
    private ngZone: NgZone,
  ) {
    this.loader = false;
    this.address = 'Pick your Location';
    this.isShow = false;
    const users = this.service.get('user').then(data => {
      if (data) {
        data = JSON.parse(data);
        this.custId = data.uid;
        this.addressService.addList(data.uid);
        this.subjectService.getAddressStateData().subscribe((state) => {
          console.log(state);
          this.addressService.defaultAddress(data.uid).then((addressData) => {
            console.log(this.addressService.defaultAdd);
            const latLng = this.addressService.defaultAdd.latLng;
            // tslint:disable-next-line:max-line-length
            this.centerService.getNearBy(latLng.latitude, latLng.longitude, this.service.distance);
            this.getAddress(latLng.latitude, latLng.longitude);
          });
        });

      }
    });

  }

  ngOnInit() {
    this.mapsAPILoader.load().then(() => {
      this.setCurrentLocation();
      this.geoCoder = new google.maps.Geocoder();
    });
    this.menuCtrl.enable(true);
  }

  resetMap() {
    console.log('called');
    const This = this;
    setTimeout(() => {
      This.mapsAPILoader.load().then(() => {
        This.setCurrentLocation();
        This.geoCoder = new google.maps.Geocoder();
        const autocomplete = new google.maps.places.Autocomplete(This.searchElementRef.nativeElement, {
          types: ['address']
        });
        autocomplete.addListener('place_changed', () => {
          This.ngZone.run(() => {
            const place: google.maps.places.PlaceResult = autocomplete.getPlace();
            if (place.geometry === undefined || place.geometry === null) {
              return;
            }
            This.lat = place.geometry.location.lat();
            This.lng = place.geometry.location.lng();
            This.getAddress(This.lat, This.lng);
            console.log(This.lat, This.lng, This.service.distance);
            This.centerService.getNearBy(This.lat, This.lng, This.service.distance);
            This.istoggle();
          });
        });
      });
    }, 1000);

  }

  private setCurrentLocation() {
    const This = this;
    if ('geolocation' in navigator) {
      navigator.geolocation.getCurrentPosition(position => {
        this.lat = position.coords.latitude;
        this.lng = position.coords.longitude;
        this.centerService.getNearBy(this.lat, this.lng, this.service.distance);
        this.getAddress(this.lat, this.lng);
      });
    }
  }

  getAddress(latitude, longitude) {
    console.log(latitude, longitude);
    this.geoCoder.geocode(
      { location: { lat: latitude, lng: longitude } },
      (results, status) => {
        console.log(results);
        console.log(status);
        if (status === 'OK') {
          if (results[0]) {
            const addressData = results[1].formatted_address.split(', ');
            this.address = addressData[0] + ', ' + addressData[1];
            console.log(this.address);
          } else {
            window.alert('No results found');
          }
        } else {
          window.alert('Geocoder failed due to: ' + status);
        }
      }
    );
  }

  setDefault(address: any) {
    this.loader = true;
    this.addressService
      .setDefaultAddress(address.addressId, this.custId)
      .then(() => {
        this.address = address.address;
        this.lat = address.latLng.latitude;
        this.lng = address.latLng.longitude;
        console.log(address.latLng);
        this.centerService.getNearBy(
          address.latLng.latitude,
          address.latLng.longitude,
          this.service.distance
        );
        this.loader = false;
      })
      .catch(err => {
        this.loader = false;
        this.service.showToast(
          'Something went wrong please try again!',
          'top',
          'my-error',
          1000
        );
      });
  }

  clickSearch() {
    this.searchShow = true;
    this.searchService.searchList = [];
  }

  searchClose() {
    this.searchShow = false;
  }

  ionViewWillEnter() {
    this.menuCtrl.enable(true);
    this.authService.checkLogin();
  }

  goToPage(path, data = null) {
    console.log(data);
    if (path === 'storelist') {
      this.service.set('centerParams', data);
    } else if (path === 'productlist') {
      this.service.set('shopParams', data);
    } else if (path === 'catstorelist') {
      this.service.set('catParams', data);
    } else {
    }
    this.router.navigateByUrl(path, { queryParams: data });
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  }

  goBack() {
    this.location.back();
  }

  istoggle() {
    this.isShow = !this.isShow;
    if (this.isShow) {
      this.resetMap();
    }
    console.log(this.isShow, 'Is SHow');
    this.subjectService.setTabData(!this.isShow);
  }

  viewPage(datas: any) {
    console.log(datas);
    let data;
    let url;
    if (datas.type === 'shopper') {
      data = datas.data;
      this.service.set('shopParams', data);
      url = 'productlist';
    } else if (datas.type === 'category') {
      data = datas.data;
      this.service.set('catParams', data);
      url = 'catstorelist';
    } else {
      data = datas.data;
      data.size = this.service.splitSep(data.size);
      data.tag = this.service.splitSep(data.tag);
      (data.color = this.service.splitSep(data.color)), (url = 'productdetail');
      this.productsService.setProd(data);
    }
    this.searchClose();
    this.router.navigateByUrl(url, { queryParams: data });
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  }

  searchFun(data: string) {
    this.searchShow = true;
    this.searchService.search(data);
  }

  async searchModal() {
    this.subjectService.setTabData(false);
    const modal = await this.modalController.create({
      component: SearchmodalPage
    });
    modal.onDidDismiss().then(dataReturned => {
      this.subjectService.setTabData(true);
    });
    return await modal.present();
  }
}
