import { Component, OnInit, NgZone, ViewChild, ElementRef } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { ValidationService } from './../../provider/validation.service';
import { WebService } from './../../provider/web.service';
import { MapsAPILoader } from '@agm/core';
import { SubjectService } from './../../provider/subject.service';
import { google } from '@google/maps';
import { ImageStorage } from '../../../environments/server.config';

declare var $;
declare const google: any;

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {
  tab: any;
  loader: boolean;
  imageUrl: any;
  user_name: string;
  vehDetails: any;
  errMessage: any;
  editProfile;
  loginDetails: any;
  selectedFile: File;
  profile_image: any;
  searchLocError: boolean;
  bookingDetails: any;
  successBookDtls: any;
  profileEditResp: any;
  autocompleteVin: any;
  autocompleteDetails: any;
  editProfileSubmitClick: boolean;
  optionalDescription: string;

  carModel: any;
  modelDates: number[] = new Array();
  carSearchJsonData: any;

  vehicleVinAddForm;
  vehicleVinFormSubmitClick;
  
  vehicleDetailsAddForm;
  vehicleDetailsFormSubmitClick;

  //Default Map Location
  lat: number = 51.678418;
  lng: number = 7.809007;

  wizardData: any;
  
  //Vehicle Details: TAB 2
  vehicleDataForm;
  vehicleDataFormSubmit;

  //Service Details: TAB 3
  issuesData: any;
  defIssuesData: any[] = new Array();
  selectedIssues: any[] = new Array();

  //Quote Page
  step: number;
  today: any = new Date();
  currDate: any;
  nextDate: any;
  dateStep: number = 0;
  activeTab: any;
  dateSection: any[] = new Array();
  imageServer: string;
  mechanicData: any;
  autoSchedule: boolean;
  showLeftArrow: boolean;
  showRightArrow: boolean;
  estimatedPrice: number;
  scheduleDateInit: boolean;
  scheduleMechanic: any;
  optionalImges: any = new Array({1:false,2:false,3:false,4:false});

  imageDisp1: any;
  imageDisp2: any;
  imageDisp3: any;
  imageDisp4: any;
  //minRoute:any;

  @ViewChild("closeWizard") public closeWizardRef: ElementRef;
  @ViewChild("googleLocVin") public googleLocVinRef: ElementRef;
  @ViewChild("goTostep1") public goTostep1Ref: ElementRef;
  @ViewChild("step2nextBtn") public step2nextRef: ElementRef;
  @ViewChild("step3nextBtn") public step3nextRef: ElementRef;
  @ViewChild("closeQuoteWizard") closeQuoteWizardRef: ElementRef;
  @ViewChild("googleLocDetails") public googleLocDetailsRef: ElementRef;
  @ViewChild("serviceHistoryTab") public serviceHistoryTabRef: ElementRef;
  @ViewChild("closeVehicleAddForm") public closeVehicleAddFormRef: ElementRef;

  constructor(private router        : Router, 
              public ngZone         : NgZone,
              private route         : ActivatedRoute,
              public mapsAPILoader  : MapsAPILoader,
              public errorMsg       : ValidationService,
              public webService     : WebService,
              public subjectService : SubjectService) {
    this.step             		          = 0;
    this.currDate                       = new Date();
    this.nextDate                       = new Date();
    this.issuesData      	            	= false;
    this.loader                         = false;
    this.activeTab                      = 'profile';
    this.errMessage                     = false;
    this.vehDetails                     = false;
    this.searchLocError                 = false;
    this.showLeftArrow    	          	= false;
    this.showRightArrow   	          	= true;
    this.scheduleDateInit               = false;
    this.editProfileSubmitClick         = false;
    this.scheduleMechanic 	            = false; 
    this.optionalDescription 	          = ''; 
    this.vehicleDetailsFormSubmitClick  = false;  
  }

  ngOnInit() {
    this.tab = 'active';

    this.route.queryParams.subscribe(params => {
      this.activeTab = params['tab'];

      if(this.activeTab == 'service'){
        this.serviceHistoryTabRef.nativeElement.click();
      }
    });

    this.vehicleVinAddForm = new FormGroup({
      vin: new FormControl('', [Validators.required]), 
      location: new FormControl('', [Validators.required])
    });

    this.vehicleDetailsAddForm = new FormGroup({
      maker: new FormControl('', [Validators.required]), 
      location: new FormControl('', [Validators.required]), 
      modelYear: new FormControl('', [Validators.required]), 
      modelName: new FormControl('', [Validators.required])
    });

    this.webService.get_stored_json('car-list.json').subscribe((response: any) => {     
      this.carSearchJsonData = response;
    });

    this.subjectService.getLoginData().subscribe(loginData => {
      this.loginDetails = JSON.parse(this.webService.getLocalStorageItem('userData'));

      if(this.loginDetails){
        this.imageUrl = ImageStorage+this.loginDetails.profile_image;
        this.editProfile = new FormGroup({
          email: new FormControl(this.loginDetails.email, [Validators.required, Validators.maxLength(50), Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$')]),
          phone: new FormControl(this.loginDetails.phone, [Validators.required, Validators.maxLength(15), Validators.pattern("^[0-9\ ( ) + , - ]+$")]),
          address: new FormControl(this.loginDetails.address, [Validators.required, Validators.maxLength(250)]),
          password: new FormControl('', [Validators.maxLength(16), Validators.minLength(6)]),
          cpassword: new FormControl('', [Validators.maxLength(16), Validators.minLength(6)]),
          last_name: new FormControl(this.loginDetails.last_name, [Validators.required, Validators.maxLength(50), Validators.pattern("^[a-zA-Z\ _ - ' \/]+$")]),
          first_name: new FormControl(this.loginDetails.first_name, [Validators.required, Validators.maxLength(50), Validators.pattern("^[a-zA-Z\ _ - ' \/]+$")])
        });
        this.getCustVehDetails();
        this.getCustBookDetails();
      } else {
        this.router.navigate(['index']);
      }
    });

    let currentYear = Number((new Date()).getFullYear());
    let startingYear = currentYear - 50;
    for (let date = currentYear ; date >= startingYear ; date --) {
      this.modelDates.push(date);
    }

    this.mapsAPILoader.load().then(() => {
      this.autocompleteVin = new google.maps.places.Autocomplete(this.googleLocVinRef.nativeElement, {
        types: ["address"]
      });
      this.autocompleteDetails = new google.maps.places.Autocomplete(this.googleLocDetailsRef.nativeElement, {
        types: ["address"]
      });
    });
    this.nextDate.setDate(this.nextDate.getDate() + 1);
  }

  getCustBookDetails(){
    this.loader = true;
    this.webService.post_data('getCustBookDetails', {'customer_id':this.loginDetails.customer_id}).subscribe(response => {
      if ( response.status == '1' && response.bookData != 'undefined' && response.bookData != undefined && response.bookData != 'null' && response.bookData != null ) {
        this.bookingDetails = response.bookData;

        let successBooking: any[] = new Array();
        this.bookingDetails.forEach(function (booking) {
          if(booking.status == 1){
            successBooking.push(booking);
          }
        });
        if(successBooking.length > 0){
          this.successBookDtls = successBooking;
        } else {
          this.successBookDtls = false;
        }
      }
      this.loader = false;
    });
  }

  getCustVehDetails(){
    this.loader = true;
    this.webService.post_data('customerVechiles', {'customer_id':this.loginDetails.customer_id}).subscribe(response => {
      if ( response.status == '1' && response.vehData != '' && response.vehData != 'undefined' && response.vehData != undefined && response.vehData != 'null' && response.vehData != null ) {
        this.vehDetails = response.vehData;
      } else {
        this.vehDetails = false;
      }
      this.loader = false;
    });
  }

  get_model(event) {
    this.carModel = this.carSearchJsonData[event].models;
  }

  setIssueSelected(event){
    let issue_id = event.target.attributes.issue_id.value;
    let sub_issue_id = event.target.attributes.sub_issue_id.value;

    const thisObj = this;
    let index = thisObj.selectedIssues.findIndex(x => x.sub_issue_id == sub_issue_id);
    if(index > -1){
      thisObj.selectedIssues.splice(index, 1);
    } else {
      thisObj.issuesData.forEach(function (issData) {
        if(issData.issue_id == issue_id){
          issData.sub_categories.forEach(function (subIssData) {
            if(subIssData.issue_cat_id == sub_issue_id){
              let issue = issData.issue, 
                  issue_image = issData.issue_image,
                  issue_category = subIssData.issue_category,
                  issue_cat_image = subIssData.issue_cat_image,
                  default_service_fee = subIssData.default_service_fee,
                  default_description = subIssData.default_description;

              thisObj.selectedIssues.push({issue_id,sub_issue_id,issue,issue_image,issue_category,issue_cat_image,default_service_fee,default_description});
            }
          });
        }
      }); 
    }
    this.calculateEstimate();
  }
  
  calculateEstimate(){
    const thisObj = this;
    thisObj.estimatedPrice = 0;
    thisObj.selectedIssues.forEach(function (selIssues) {
      thisObj.estimatedPrice = thisObj.estimatedPrice + Number(selIssues.default_service_fee);
    });
  }

  removeSelectedItem(issue_id,sub_issue_id){
    let index = this.selectedIssues.findIndex(x => x.sub_issue_id == sub_issue_id);
    if(index > -1){
      this.selectedIssues.splice(index, 1);

      $('[id="issue_'+issue_id+'_'+sub_issue_id+'"]').prop('checked', false);
    }
    if(this.selectedIssues.length == 0){
      this.goTostep1Ref.nativeElement.click();
    }
    this.calculateEstimate();
  }

  submitProfileEdit(data){
    if(this.editProfile.invalid){
      return false;
    }
    const This = this;
    this.loader = true;
    data.customer_id = this.loginDetails.customer_id;

    let formData: FormData = new FormData();
    formData.append('data', JSON.stringify(data));

    if(this.profile_image && this.profile_image != '' && this.profile_image != undefined && this.profile_image != 'undefined' && this.profile_image != null && this.profile_image != 'null'){
      formData.append('profile_image', this.profile_image);
    }

    this.webService.multipart_post('edit_customer_profile', formData).subscribe(response => {
      if ( response.status == '1') {
        const userData = this.webService.getLocalStorageItem('userData');
        this.webService.removeLocalStorageItem(userData);

        let ret_profile_image = (response.profile_image && response.profile_image != undefined && response.profile_image != 'undefined' && response.profile_image != null && response.profile_image != 'null')?response.profile_image:this.loginDetails.profile_image;
        this.imageUrl = ImageStorage+ret_profile_image;

        let newUserData = {"customer_id":this.loginDetails.customer_id,
                           "phone":data.phone,
                           "email":data.email,
                           "address":data.address,
                           "last_name":data.last_name,
                           "first_name":data.first_name,
                           "profile_image":ret_profile_image,
                           "status":"1"}
        this.webService.setLocalStorageItem('userData', JSON.stringify(newUserData));

        response.status = 'success';
        this.profileEditResp = response;
        this.loader = false;
      } else {
        response.status = 'error';
        response.message = (response.message == '')?this.errorMsg.errorList.req_failure:response.message; 

        this.profileEditResp = response;
        this.loader = false;
      }
    },error => {
      this.loader = false;
      this.profileEditResp = {'status':'error','message':this.errorMsg.errorList.req_failure};
    },() => {
      setTimeout( function() {
        This.profileEditResp = false;
      }, 2000)
    });
  }

  vehicleDetailsFormSubmit(vehicleData){
    if(this.vehicleDetailsAddForm.invalid){
      this.vehicleDetailsFormSubmitClick = true;
      return false;
    }
    let location;
    this.vehicleDetailsFormSubmitClick = false;
    vehicleData.car_maker = this.carSearchJsonData[vehicleData['maker']]['brand'];
    this.ngZone.run(() => {
      let place: google.maps.places.PlaceResult = this.autocompleteDetails.getPlace();
      if (place == undefined || place == null || place === undefined || place === null || 
          place.geometry == undefined || place.geometry == null || place.geometry === undefined || place.geometry === null || 
          place.formatted_address == undefined || place.formatted_address == null || place.formatted_address === undefined || place.formatted_address === null) {
          this.searchLocError = true;
        return;
      }

      location = {'location':place.formatted_address,
                  'location_lat':place.geometry.location.lat(),
                  'location_lng':place.geometry.location.lng()
                 };
    });

    this.addCustomerCar(1,vehicleData,location);
  }
  
  vehicleVinFormSubmit(vehicleData){
    if(this.vehicleVinAddForm.invalid){
      this.vehicleVinFormSubmitClick = true;
      return false;
    }

    let location;
    this.vehicleVinFormSubmitClick = false;
    this.ngZone.run(() => {
      let place: google.maps.places.PlaceResult = this.autocompleteVin.getPlace();
      if (place == undefined || place == null || place === undefined || place === null || 
          place.geometry == undefined || place.geometry == null || place.geometry === undefined || place.geometry === null || 
          place.formatted_address == undefined || place.formatted_address == null || place.formatted_address === undefined || place.formatted_address === null) {
          this.searchLocError = true;
        return;
      }

      location = {'location':place.formatted_address,
                  'location_lat':place.geometry.location.lat(),
                  'location_lng':place.geometry.location.lng()
                 };
    });

    this.addCustomerCar(2,vehicleData,location);
  }

  addCustomerCar(type,vehicleData,location){
    this.loader = true;
    let postData = {'type':type,'customer_id':this.loginDetails.customer_id,'vehicleData':vehicleData,'location':location};

    this.webService.post_data('addCustomerCar',postData).subscribe(response => {
      if ( response.status == '1' ) {
        this.getCustVehDetails();
        this.closeVehicleAddFormRef.nativeElement.click();
        this.resetVehicleForm();
        this.loader = false;
      } else {
        this.loader = false;
        this.errMessage = {'errMsg':response.message}
        setTimeout (() => {
          this.errMessage = false;
        }, 2000);
      }
    });
  }

  cancelBooking(bookingId){
    this.loader = true;
    this.webService.post_data('cancelBooking', {'customer_id':this.loginDetails.customer_id,'booking_id':bookingId}).subscribe(response => {
      if ( response.status == '1' ) {
        this.getCustBookDetails();
        this.loader = false;
      }
    });
  }

  deleteCustomerCar(customer_id,customer_veh_id){
    this.loader = true;
    this.webService.post_data('deleteCustomerCar', {'customer_id':customer_id,'customer_veh_id':customer_veh_id}).subscribe(response => {
      if ( response.status == '1' ) {
        this.getCustVehDetails();
        this.loader = false;
      }
    });
  }

  optImgUpload(image_id,event){
    let reader = new FileReader();
    let optionalImg: any = event.target.files[0];

    reader.onloadend = () => {
      switch (image_id){
        case 1:
          this.optionalImges[1] = {'file':event.target.files[0],'file_url':reader.result};
          break;
        case 2:
          this.optionalImges[2] = {'file':event.target.files[0],'file_url':reader.result};
          break;
        case 3:
          this.optionalImges[3] = {'file':event.target.files[0],'file_url':reader.result};
          break;
        case 4:
          this.optionalImges[4] = {'file':event.target.files[0],'file_url':reader.result};
          break;
      }
    }
    reader.readAsDataURL(optionalImg);
  }

  imageUpload(e) {
    let reader = new FileReader();
    this.profile_image = e.target.files[0];
    reader.onloadend = () => {
      this.imageUrl = reader.result;
    }
    reader.readAsDataURL(this.profile_image);
  }

  resetVehicleForm(){
    this.vehicleVinAddForm.reset();
    this.vehicleDetailsAddForm.reset({
      maker: '', modelYear: '', modelName: '', location: ''
    });
  }

  routeToIndex(){
    this.router.navigate(["index"]);
  }

  bookVechile(customer_veh_id){
    this.loader = true;

    const thisObj = this;
    thisObj.vehDetails.forEach(function (vehData) {
      if(vehData.customer_veh_id == customer_veh_id){
        thisObj.wizardData = {'pickup_data': 
                            {'pickup_loc':vehData.car_location,
                             'pickup_lat':vehData.car_loc_lat,
                             'pickup_lng':vehData.car_loc_lng
                            }
                          };

        thisObj.wizardData['vechile_info'] = {'trim':'','milage':'','emgine':'',
                                           'maker':vehData.car_maker,
                                           'modelName':vehData.car_model,
                                           'modelYear':vehData.car_model_year}
      }
    });
    this.getIssueData();
  }

  getIssueData(){
    const This = this;
    this.loader = true;
    this.webService.get_data('getGeneralIssues').subscribe(response => {
      if(response.status == '1'){
        this.issuesData = response.issue_data;
        this.defIssuesData = this.issuesData;
        this.loader = false;
      } else {
        this.loader = false;
        return false;
      }
    },error => {
      this.loader = false;
      return false;
    });
  }

  searchIssues(event){
    if(event.target.value == '' || event.target.value == 'undefined' || event.target.value == undefined || event.target.value == 'null' || event.target.value == null ){
      this.issuesData = this.defIssuesData;
    } else {
      const thisObj = this;
      let data: any[] = new Array();
      let serRegExp = new RegExp(event.target.value,"gi");

      thisObj.defIssuesData.forEach(function (issues,index) {
        let issueCat = issues.issue;

        if(issueCat.search(serRegExp) != -1){
          data.push(thisObj.defIssuesData[index]);
        }
      });
      this.issuesData = (data.length > 0)?data:false;
    }

    setTimeout(()=>{
      this.selectedIssues.forEach(function (issues) {
        $('[id="issue_'+issues.issue_id+'_'+issues.sub_issue_id+'"]').prop('checked', true);
      });
    },500);
  }

  jumpToStep3(){
    if(this.selectedIssues.length != 0){
      this.step3nextRef.nativeElement.click();
    }
  }

  getQuote(){
    const thisObj = this;
    this.loader = true;

    let selSubIssues: any[] = new Array();
    thisObj.selectedIssues.forEach(function (selIssues) {
      selSubIssues.push(selIssues.sub_issue_id);
    });

    let searchData = {'pickup_data':this.wizardData.pickup_data,'sub_issues':selSubIssues}
    this.webService.post_data('getNearByMechanics',searchData).subscribe(response => {
      if(response.status == '1'){
        this.mechanicData = response.mechanic_data;
        
        this.dateSection.push(new Date(this.today.setDate(this.today.getDate())));
        this.dateSection.push(new Date(this.today.setDate(this.today.getDate() + 1)));

        this.loader = false;
      } else {
        this.loader = false;
        return false;
      }
    },error => {
      this.loader = false;
      return false;
    });
  }

  onMouseOver(infoWindow, gm) {
    if (gm.lastOpen != null) {
        gm.lastOpen.close();
    }
    gm.lastOpen = infoWindow;
    infoWindow.open();
  }

  onMouseOut(gm){
    if (gm.lastOpen != null) {
      gm.lastOpen.close();
    }
  }

  next(event) {
    if(this.dateStep > 30){
      this.showLeftArrow = true;
      this.showRightArrow = false;
      return false;
    }
    this.showLeftArrow = true;
    this.showRightArrow = true;
    this.dateSection = new Array();
    this.nextDate.setDate(this.nextDate.getDate() + 1);
    this.currDate.setDate(this.currDate.getDate() + 1);
    this.dateSection[0] = new Date(this.currDate);
    this.dateSection[1] = new Date(this.nextDate);
    this.dateStep += 1;
  }

  prev(event) {
    if(this.dateStep <= 0){
      this.showLeftArrow = false;
      this.showRightArrow = true;
      return false;
    }
    this.showLeftArrow = true;
    this.showRightArrow = true;
    this.dateSection = new Array();
    this.nextDate.setDate(this.nextDate.getDate() - 1);
    this.currDate.setDate(this.currDate.getDate() - 1);
    this.dateSection[0] = new Date(this.currDate);
    this.dateSection[1] = new Date(this.nextDate);
    this.dateStep -= 1;
  }

  getSchedule(time,index){
    this.wizardData['schedule_date'] = {'date':this.formatDate(this.dateSection[index]),'time':time};
  }

  formatDate(date) {
    const d = new Date(date);
    let day = '' + d.getDate();
    let month = ''+(d.getMonth()+1);
    const year = d.getFullYear();
    if (day.length < 2) { day = '0'+day; }
    if (month.length < 2) { month = '0'+month; }
    return [year,month,day].join('-');
  }

  scheduleNow(mechanic_id,cost){
    this.wizardData['mechanic_id'] = mechanic_id;

    if(!this.loginDetails){
      this.routeToIndex();
    }
    this.loader = true;

    this.wizardData['cost'] = cost;
    this.confirmBooking();
  }

  confirmBooking(){
    this.wizardData['customer_id'] = this.loginDetails.customer_id;
    this.wizardData['selected_issues'] = this.selectedIssues;
    this.wizardData['optionalDescription'] = this.optionalDescription;

    let formData: FormData = new FormData();
    formData.append('data', JSON.stringify(this.wizardData));

    this.optionalImges.forEach(function (imgData,index) {
      if(!imgData){
        return true;
      }
      formData.append("optFile_" + (index), imgData.file);
    });

    this.webService.multipart_post('scheduleNow', formData).subscribe(response => {
    // this.webService.post_data('scheduleNow',this.wizardData).subscribe(response => {
      if(response.status == '1'){
        this.closeWizardRef.nativeElement.click();
        this.closeQuoteWizardRef.nativeElement.click();
        
        this.goTostep1Ref.nativeElement.click();
        this.selectedIssues = [];

        this.serviceHistoryTabRef.nativeElement.click();
        
        this.getCustBookDetails();
      } else {
        this.loader = false;
        return false;
      }
    },error => {
      this.loader = false;
      return false;
    });
  }

  resetQuoteWizard(){
    this.selectedIssues = [];
    this.scheduleMechanic = false;
    this.scheduleDateInit = false;
    this.goTostep1Ref.nativeElement.click();

    this.optionalImges[1] = false;
    this.optionalImges[2] = false;
    this.optionalImges[3] = false;
    this.optionalImges[4] = false;
    this.optionalDescription = '';
  }

  scrollToBottom(id){
    $('#'+id).stop().animate({scrollTop: $('#'+id)[0].scrollHeight}, 1500);
  }

  tab_swap(type) { this.tab = type; }
}
