import { Component, OnInit } 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 = false;
  searchShow = false;
  public lat = 51.678418;
  public lng = 7.809007;
  loader: boolean;
  address: any;
  custId: any;
  private geoCoder;
  subscription: any;
  slideOpts = {
    slidesPerView: 1.5
  };

  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
  ) {
    this.loader = false;
    this.address = 'Pick your Location';
  }

  ngOnInit() {
    this.mapsAPILoader.load().then(() => {
      this.setCurrentLocation();
      this.geoCoder = new google.maps.Geocoder();
    });
    this.menuCtrl.enable(true);
    const users = this.service.get('user').then(data => {
      if (data) {
        data = JSON.parse(data);
        this.custId = data.uid;
        this.addressService.addList(data.uid);
      }
    });
  }

  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) {
    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;
        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;
    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();
  }
}
