import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import * as moment from 'moment';
import { of } from 'rxjs';
import { CommonFunctionService } from 'src/app/core/common/common-function.service';
import { ValidationService } from 'src/app/core/common/validation.service';
import { API } from 'src/app/core/services/api.service';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'app-vehicle-master-add',
  templateUrl: './vehicle-master-add.component.html',
})
export class VehicleMasterAddComponent implements OnInit {
  Edit_Id: string;
  VehicleForm: FormGroup;
  AllLang;
  transferVendorList;
  fileInfo = [];
  fileArr = [];
  vehicleTypeList = [
    { key: 'Standard', value: 'STANDARD' },
    { key: 'Sedan', value: 'SEDAN' },
    { key: 'Minivan', value: 'MINIVAN' },
    { key: 'Minbus', value: 'MINBUS' },
    { key: 'Luxury Sedan', value: 'LUXURYSEDAN' },
    { key: 'Luxury Minivan', value: 'LUXURYMINIVAN' },
    { key: 'SUV', value: 'SUV' },
    { key: 'Minicoach', value: 'MINICOACH' },
    { key: 'Bus', value: 'BUS' }
  ];
  passCapacityList = Array.from({ length: 100 }, (_, i) => i + 1);
  editResp: any;

  constructor(public fb: FormBuilder, public validServ: ValidationService, private apiserv: API, private commonMasterSer: CommonFunctionService, private router: Router, private activateRoute: ActivatedRoute) {

  }

  ngOnInit(): void {
    this.Edit_Id = this.activateRoute.snapshot.paramMap.get('RuleId') as string;
    this.initform();
    this.GetAllLAng();
    this.GetTransferVendor()
    if (this.Edit_Id) {
      this.GetById();
    }
  }
  GetAllLAng() {
    this.apiserv.AdminGet('/LanguageMapping/GetLanguagesByOrgId').subscribe(data => {
      if (data) {
        this.AllLang = data;
      }
    })
  }
  GetTransferVendor() {
    this.apiserv.Get('/ActivityVehicle/GetVehicleVendor').subscribe(res => {
      if (res) {
        this.transferVendorList = res.data;
      }
    })
  }

  initform() {
    this.VehicleForm = this.fb.group({
      vehicleType: this.validServ.required,
      defaultLanguageCode: this.validServ.required,
      maxPassengerCapacity: this.validServ.required,
      maxLuggageCapacity: this.validServ.required,
      vehicleNumberPlate: '',
      vehicleTransferType: this.validServ.required,
      displayVehicleImage: '',
      displayVehicleImageUrl: '',
      vehicleImages: this.fb.control([]),
      vehicleImagesUrl: this.fb.control([]),
      fuelType: '',
      vehicleName: '',
      VehicleDescription: '',
      vehicleVendorId: '',
    })
  }

  SelectImage(e, filedata, contol) {
    if (e.currentFiles.length != 0) {
      for (let i = 0; i < e.files.length; i++) {
        let file = e.files[i];
        if (file.size < 1048576 && (file.type == 'image/png' || file.type == 'image/jpeg')) {
          const reader = new FileReader();
          console.log(file)
          reader.readAsText(file); // Read as binary data
          reader.onload = (res) => {
            const binaryString = res.target.result as string;
            const hasScriptTag = this.commonMasterSer.hasScriptTagInBinary(binaryString);
            if (hasScriptTag) {
              filedata.clear();
              this.commonMasterSer.showMessage(false, 'Invalid file (contains script tag)');
            } else {
              //base 64
              if (contol == 'displayVehicleImage') {
                this.VehicleForm.get(contol).setValue(file);
              } else {
                this.VehicleForm.get(contol).value.push(file);
              }
              const reader = new FileReader();
              reader.readAsDataURL(file);
              reader.onload = () => {
                if (contol == 'displayVehicleImage') {
                  this.VehicleForm.get('displayVehicleImageUrl').setValue(reader.result.toString());
                } else {
                  this.VehicleForm.get('vehicleImagesUrl').value.push(reader.result.toString());
                }
              }
            };
          }
        }
      }
    }

  }
  RemoveImage(ind, contol) {
    if (contol == 'displayVehicleImage') {
      this.VehicleForm.get(contol).setValue('');
      this.VehicleForm.get('displayVehicleImageUrl').setValue('');
    } else {
      let image_url_list = this.VehicleForm.get(contol).value;
      image_url_list.splice(ind, 1);
      let image_display_url_list = this.VehicleForm.get('vehicleImagesUrl').value;
      image_display_url_list.splice(ind, 1);
    }
  }

  GetById() {
    this.apiserv.Get(`/ActivityVehicle/GetById/${this.Edit_Id}`).subscribe(res => {
      if (res && res.status) {
        this.editResp = res.data;
        this.VehicleForm.get('vehicleType').setValue(this.editResp.vehicleType);
        this.VehicleForm.get('defaultLanguageCode').setValue(this.editResp.defaultLanguageCode);
        this.VehicleForm.get('maxPassengerCapacity').setValue(this.editResp.maxPassengerCapacity);
        this.VehicleForm.get('maxLuggageCapacity').setValue(this.editResp.maxLuggageCapacity);
        this.VehicleForm.get('vehicleNumberPlate').setValue(this.editResp.vehicleNumberPlate);
        this.VehicleForm.get('vehicleTransferType').setValue(this.editResp.vehicleTransferType);
        this.VehicleForm.get('fuelType').setValue(this.editResp.fuelType);
        this.VehicleForm.get('vehicleName').setValue(this.editResp.activityVehicleDetails.vehicleName);
        this.VehicleForm.get('vehicleVendorId').setValue(this.editResp.activityVehicleDetails.vehicleVendorId || '');
        this.VehicleForm.get('VehicleDescription').setValue(this.editResp.activityVehicleDetails.VehicleDescription);
        if (this.editResp.vehicleImages) {
          let Images_Arr = this.editResp.vehicleImages.split(',');
          Images_Arr.forEach(data => {
            this.VehicleForm.get('vehicleImages').value.push(data);
            this.VehicleForm.get('vehicleImagesUrl').value.push(data);
          })
        }
        if (this.editResp.displayVehicleImage) {
          this.VehicleForm.get('displayVehicleImage').setValue(this.editResp.displayVehicleImage);
          this.VehicleForm.get('displayVehicleImageUrl').setValue(this.editResp.displayVehicleImage);
        }
      }
    })
  }

  SaveUpdateVehicleDet() {
    if (this.VehicleForm.status == "INVALID") {
      this.validServ.showValidationsMsg(this.VehicleForm);
      setTimeout(() => {
        this.validServ.scrollToError();
      }, 50);
    } else if (this.VehicleForm.status == "VALID") {
      let formVal = this.VehicleForm.getRawValue();
      let postData = {
        vehicleType: formVal.vehicleType,
        ActivityVehicleId: this.Edit_Id ?? '',
        defaultLanguageCode: formVal.defaultLanguageCode,
        maxPassengerCapacity: formVal.maxPassengerCapacity.toString(),
        maxLuggageCapacity: formVal.maxLuggageCapacity,
        vehicleNumberPlate: formVal.vehicleNumberPlate,
        vehicleTransferType: formVal.vehicleTransferType,
        displayVehicleImage: formVal,
        vehicleImages: formVal,
        fuelType: formVal.fuelType,
        vehicleVendorId: formVal.vehicleVendorId,
        activityVehicleDetails: {
          vehicleName: formVal.vehicleName,
          VehicleDescription: formVal.VehicleDescription,
          LanguageCode: formVal.defaultLanguageCode,
          ActivityVehicleId: this.Edit_Id ?? '',
          activityVehicleDetailsId: this.editResp ?this.editResp.activityVehicleDetails.activityVehicleDetailsId :''
        },
      }
      let vehicleImages_arr = []
      formVal.vehicleImages.forEach((img_data, img_Ind) => {
        if (typeof (img_data) == 'object' && img_data) {
          let image_type = img_data.name.split('.');
          this.fileArr.push(img_data);
          this.fileInfo.push({ 'fileName': "Extranet/Activity/Vehicle/ActivityVehicleId/vehicleImages_" + img_Ind + '.' + image_type[image_type.length - 1], 'pathToSave': 'OrganizationData/ORGID' });
          let image_url = `${environment.cdnFileUrl}OrganizationData/ORGID/Extranet/Activity/Vehicle/ActivityVehicleId/vehicleImages_${img_Ind}.${image_type[image_type.length - 1]}?t=${moment(new Date()).format("yyMMddHHmmssfffffff")}`;
          vehicleImages_arr.push(image_url)
        } else {
          vehicleImages_arr.push(img_data);
        }
      })
      let thumbnail_image_url = '';
      if (typeof (formVal.displayVehicleImage) == 'object' && formVal.displayVehicleImage) {
        let image_type = formVal.displayVehicleImage.name.split('.');
        this.fileArr.push(formVal.displayVehicleImage);
        this.fileInfo.push({ 'fileName': "Extranet/Activity/Vehicle/ActivityVehicleId/DisplayImg" + '.' + image_type[image_type.length - 1], 'pathToSave': 'OrganizationData/ORGID' });
        thumbnail_image_url = `${environment.cdnFileUrl}OrganizationData/ORGID/Extranet/Activity/Vehicle/ActivityVehicleId/DisplayImg.${image_type[image_type.length - 1]}?t=${moment(new Date()).format("yyMMddHHmmssfffffff")}`;
      } else {
        thumbnail_image_url = formVal.displayVehicleImage;
      }
      postData['vehicleImages'] = vehicleImages_arr.length > 0 ? vehicleImages_arr.join(',') : '';
      postData['displayVehicleImage'] = thumbnail_image_url;
      let url = this.Edit_Id  ?  `Update` : 'Save';
      this.apiserv.Post(`/ActivityVehicle/${url}`, postData).subscribe(resp => {
        if (resp) {
          if (this.fileInfo.length > 0 && resp.status) {
            this.saveImg(this.fileInfo, this.fileArr, resp.data).subscribe(res => {
              if (res && res.resp) {
                this.BackButton();
              }
              this.commonMasterSer.showMessage(resp.resp, resp.message)
            })
          } else if (resp.status) {
            this.BackButton();
          }
          this.commonMasterSer.showMessage(resp.status, resp.message);

        }
      })
    }
  }

  saveImg(fileInfo, fileArr, edit_id) {
    if (fileInfo && fileInfo.length > 0 && fileArr && fileArr.length > 0) {
      var formdata = new FormData();
      fileArr.forEach((x) => {
        formdata.append("files", x);
      });
      let file_info_list = JSON.stringify(fileInfo).replaceAll('ActivityVehicleId', edit_id);
      formdata.append("fileInfo", file_info_list);
      return this.apiserv.PostFile("/FileUpload/SaveFile", formdata);
    } else {
      return of({
        resp: true,
        respMsg: "No images to save"
      });
    }
  }
  BackButton() {
    this.router.navigateByUrl(`ActivityConfiguration/VehicleMaster/Search`);
  }

}
