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

declare var $;
declare const google: any;

@Component({
  selector: 'app-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.scss']
})


export class IndexComponent implements OnInit {
  public featuredOn: NgxCarousel;
  public carouselTile: NgxCarousel;

  @ViewChild('wizardModal') wizardModalTrrigerInput;

  //Default Map Location

  lat: number = 51.678418;
  lng: number = 7.809007;

  wizardData: any;
  loginDetails: any;

  //Basic Location Search: TAB 1

  autocomplete: any;
  cfautocomplete: any;
  searchLocError: boolean;
  addresssearchLocError: boolean;
  @ViewChild("goTostep0") public goTostep0Ref: ElementRef;
  @ViewChild("goTostep1") public goTostep1Ref: ElementRef;
  @ViewChild("goTostep2") public goTostep2Ref: ElementRef;
  
  @ViewChild("closeWizard") public closeWizardRef: ElementRef;
  @ViewChild("googleLocSearch") public searchElementRef: ElementRef;
  @ViewChild("addressLocSearch") public addressElementRef: ElementRef;
  @ViewChild("indexLoginModal") loginModalRef: ElementRef;
  @ViewChild("closeQuoteWizard") closeQuoteWizardRef: ElementRef;

  //Vehicle Details: TAB 2
  vehicleDataForm;
  vehicleDataFormSubmit;

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

  public scrollbarOptions = { axis: 'y', theme: 'minimal-dark' };

  //Quote Page
  step: number;
  today: any = new Date();
  currDate: any;
  nextDate: any;
  dateStep: number = 0;
  mechanics: string = ''; 
  dateSection: any[] = new Array();
  selMechanics: any[] = new Array();
  imageServer: string;
  mechanicData: any;
  autoSchedule: boolean;
  showLeftArrow: boolean;
  showRightArrow: boolean;
  estimatedPrice: number;
  scheduleDateInit: boolean;
  scheduleMechanic: any;

  carModel: any;
  modelDates: number[] = new Array();
  carSearchJsonData: any;
  optionalImges: any = new Array({1:false,2:false,3:false,4:false});
  optionalDescription: string;

  constructor(
    private router        : Router, 
    public ngZone         : NgZone,
    public webService     : WebService,
    public mapsAPILoader  : MapsAPILoader,
    public subjectService : SubjectService) { 
      this.step             = 0;
      this.issuesData       = false;
      this.autoSchedule     = false;
      this.imageServer      = ImageStorage;
      this.currDate         = new Date();
      this.nextDate         = new Date();
      this.loginDetails     = false;
      this.searchLocError   = false;
      this.addresssearchLocError   = false;
      this.showLeftArrow    = false;
      this.showRightArrow   = true;
      this.scheduleDateInit = false;
      this.scheduleMechanic = false;
      this.optionalDescription   = '';
      this.vehicleDataFormSubmit = false;
    }

  ngOnInit() {
    this.vehicleDataForm = new FormGroup({
      trim: new FormControl(''), milage: new FormControl(''), emgine: new FormControl(''),
      last_date: new FormControl(''), 
      maintanence_interval: new FormControl(''), 
      maker: 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;
    });
    
    let currentYear = Number((new Date()).getFullYear());
    let startingYear = currentYear - 50;
    for (let date = currentYear ; date >= startingYear ; date --) {
      this.modelDates.push(date);
    }

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

      if(this.loginDetails && this.autoSchedule){
        this.confirmBooking();
      }
    });

    this.mapsAPILoader.load().then(() => {
      this.autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
        types: ["address"]
      });
      this.cfautocomplete = new google.maps.places.Autocomplete(this.addressElementRef.nativeElement, {
        types: ["address"]
      });
    });

    this.featuredOn = {grid: {xs: 1, sm: 2 , md: 5, lg: 6, all: 0},slide: 1, speed: 400, animation: 'lazy',point: { visible: false },load: 2, touch: true, easing: 'ease'}
    this.carouselTile = {grid: {xs: 1, sm: 2 , md: 3, lg: 3, all: 0},slide: 1, speed: 400, animation: 'lazy',point: { visible: false },load: 2, touch: true, easing: 'ease'}
    this.nextDate.setDate(this.nextDate.getDate() + 1);

    $('.modal-backdrop').remove();
    $('body').attr('class','');
    $('body').attr('style','');
  }

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

  getVehicleLoc(lastLoc){
    if(lastLoc == ''){
      this.searchLocError = true;
      return;
    }
    this.ngZone.run(() => {
      let place: google.maps.places.PlaceResult = this.autocomplete.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;
      }
      this.wizardData = {'pickup_data': 
                          {'disp_loc':place.name,
                           'pickup_loc':place.formatted_address,
                           'pickup_lat':place.geometry.location.lat(),
                           'pickup_lng':place.geometry.location.lng()
                          }
                        };

      this.searchLocError = false;
      this.lat = place.geometry.location.lat();
      this.lng = place.geometry.location.lng();
      this.wizardModalTrrigerInput.nativeElement.click();
      
      this.getIssueData();
    });
  }

  getVehicleData(vehicleData){
    if(this.vehicleDataForm.invalid){
      this.vehicleDataFormSubmit = true;
      return false;
    }
    this.wizardData['vechile_info'] = {'trim':vehicleData['trim'],
                                       'lastMaintanceDate':(vehicleData['last_date'])?(formatDate(vehicleData['last_date'],'MM/dd/yyyy','en')):'',
                                       'maker':this.carSearchJsonData[vehicleData['maker']]['brand'],
                                       'milage':vehicleData['milage'],'emgine':vehicleData['emgine'],
                                       'modelName':vehicleData['modelName'],'modelYear':vehicleData['modelYear'],
                                       'maintanenceInterval':vehicleData['maintanence_interval']
                                      }
    console.log(this.wizardData['vechile_info'])                                 
    this.vehicleDataFormSubmit = false;
  }

  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 subCatArr: any;
      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]);
        } else {
          subCatArr = issues.sub_categories;
          subCatArr.forEach(function (issues_cat) {
            let sub_issue_cat = issues_cat.issue_category;
            if(sub_issue_cat.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);
  }
  get_newlocaion(lastLoc){
    this.cfautocomplete.addListener("place_changed", () => {
      this.ngZone.run(() => {
        let places: google.maps.places.PlaceResult = this.cfautocomplete.getPlace();
        if (places == undefined || places == null || places === undefined || places === null || 
            places.geometry == undefined || places.geometry == null || places.geometry === undefined || places.geometry === null || 
            places.formatted_address == undefined || places.formatted_address == null || places.formatted_address === undefined || places.formatted_address === null) {
            this.addresssearchLocError = true;
          return;
        }
        this.wizardData['pickup_data'] = {
                                          'disp_loc':places.name,
                                          'pickup_loc':places.formatted_address,
                                          'pickup_lat':places.geometry.location.lat(),
                                          'pickup_lng':places.geometry.location.lng()
                                        };
        this.addresssearchLocError = false;
        this.lat = places.geometry.location.lat();
        this.lng = places.geometry.location.lng();
      });
    })
  }
  
  get_newdate(lastdate){
    this.wizardData['vechile_info']['lastMaintanceDate']=formatDate(lastdate,'MM/dd/yyyy','en');
  }

  get_newmilage(milage){
    this.wizardData['vechile_info']['milage']=milage;
  }

  get_newmaintanence_date(newdate){
    this.wizardData['vechile_info']['maintanenceInterval']=newdate.target.value;
  }

  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.jumpToStep1();
    }
    this.calculateEstimate();
  }

  resetQuoteWizard(){
    this.jumpToStep0();
    this.searchElementRef.nativeElement.value = '';
    
    this.selectedIssues = [];

    this.vehicleDataForm.reset({
      trim: '', milage: '', emgine: '', maker: '', modelYear: '', modelName: ''
    });

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

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

    let selSubIssues: any[] = new Array();
    thisObj.selectedIssues.forEach(function (selIssues) {
      selSubIssues.push(selIssues.sub_issue_id);
    });
    console.log(this.wizardData)
    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.autoSchedule = true;
      this.loginModalRef.nativeElement.click();
      return false;
    }
    this.loader = true;
    
    this.wizardData['cost'] = cost;
    this.confirmBooking();
  }

  scheduleMultipleRequest(){
    if(!this.loginDetails){
      this.autoSchedule = true;
      this.loginModalRef.nativeElement.click();
      return false;
    }
    let coma = '';
    const thisObj = this;
    this.mechanics = '';
    this.selMechanics.forEach(function (mechanic_data) {
      thisObj.mechanics += coma+mechanic_data.mechanic_id+':'+mechanic_data.amount; 
      coma = ',';
    })       
    this.wizardData['mechanic_id'] = thisObj.mechanics;
    this.wizardData['cost'] = this.estimatedPrice;
    this.wizardData['multiple'] ='1';
    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.router.navigate(['../dashboard'],{queryParams: {tab: 'service'}});
      } else {
        this.loader = false;
        return false;
      }
    },error => {
      this.loader = false;
      return false;
    });
  }

  jumpToStep0(){
    this.goTostep0Ref.nativeElement.click();
  }

  jumpToStep1(){
    if(!this.vehicleDataForm.invalid){
      this.goTostep1Ref.nativeElement.click();
    }
  }

  jumpToStep2(){
    if(this.selectedIssues.length > 0){
      this.goTostep2Ref.nativeElement.click();
    }
  }
  
  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);
  }

  checkboxChange(index,mechanic_id,event,estimate){
    if (event.target.checked) {
      this.selMechanics.push({id:index,mechanic_id:mechanic_id,amount:estimate});
    } else {
      let id = this.selMechanics.findIndex(x => x.id == index);
      if (id != -1) {
        this.selMechanics.splice(id, 1);
      }
    }
  }

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

  scrollToTop(id){
    $('#'+id).stop().animate({scrollTop: 0}, 800);
  }

  featuredOnLoad() {return ''; }
  carouselTileLoad(){ return ''; }
}
