import { ActivatedRoute, Params } from '@angular/router';
import { AuthServiceService } from './../../shared/auth-service.service';
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { MouseEvent } from '@agm/core';
import { NgxSpinnerService } from 'ngx-spinner';
import { ToastrService } from 'ngx-toastr';


@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.css']
})
export class MapComponent implements OnInit {

  constructor(private http: HttpClient, 
    private spinner: NgxSpinnerService, 
    private toastr: ToastrService,
    private route: ActivatedRoute,

    private authSer: AuthServiceService) { 
    this.spinner.show();
  }

  lat: number =  24.380000;//51.673858;
  lng: number = 46.430000;  //= 7.815982;

  zoom: number = 8;

pageId: number;

  
  markers: marker[] = [
	  {
		  lat: 46.430000,
		  lng: 46.430000,
		  label: 'A',
		  draggable: true
	  }
  ];


  ngOnInit() {
    

    this.route.params.subscribe(
      (params: Params) => {
        this.pageId = +params['listPageId'];
        localStorage.setItem('pageIdActive', params['listPageId']);
      }
    );


    this.http.get(this.authSer.pathApi + '/get_reach_map/1').subscribe(
      (responce) => {
        console.log(responce);
        this.lat = responce['reach_map'].latitude;
        this.lng = responce['reach_map'].longitude;
        this.markers[0].lat = responce['reach_map'].latitude
        this.markers[0].lng = responce['reach_map'].longitude
        this.spinner.hide();
      },
      (error) => {
        console.log(error);
      }
    );

  }

  clickedMarker(label: string, index: number) {
    console.log(`clicked the marker: ${label || index}`)
  }

  mapClicked($event: MouseEvent) {
    
    this.markers[0].lat = $event.coords.lat;
    this.markers[0].lng = $event.coords.lng;
    // this.markers.push({
    //   lat: $event.coords.lat,
    //   lng: $event.coords.lng,
    //   draggable: true
    // });

   
  }

  markerDragEnd(m: marker, $event: MouseEvent) {
    console.log('dragEnd', m, $event);
    this.markers[0].lat = $event.coords.lat;
    this.markers[0].lng = $event.coords.lng;
    console.log('wwwwwwwwwwwwwwwwwwwwww' , this.markers);
  }


saveLocation() {
  console.log(this.markers);
  
  const dataMap={
    latitude: this.markers[0].lat,
    longitude: this.markers[0].lng,
    id: 1
  }

  console.log('responce map', dataMap);

  this.http.post(this.authSer.pathApi + '/edit_reach_map', dataMap).subscribe(
    (responce) => {
      console.log(responce);
      this.toastr.success('تم حفظ الموقع');
    },
    (error) => {
      console.log(error);
      this.toastr.error('خطأ في الموقع إنتظر قليلاً');
    }
  );

}

  

}




  // just an interface for type safety.
  interface marker {
    lat: number;
    lng: number;
    label?: string;
    draggable: boolean;
  }
