Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
24 kB
2
Indexable
Never
import { IBlock } from "../../../framework/src/IBlock";
import { Message } from "../../../framework/src/Message";
import { BlockComponent } from "../../../framework/src/BlockComponent";
import MessageEnum, {
  getName,
} from "../../../framework/src/Messages/MessageEnum";
import { runEngine } from "../../../framework/src/RunEngine";

// Customizable Area Start
import {
  pencilVector,
  bluetooth,
  play,
  video,
  poolIcon,
  hotTubIcon,
  patioIcon,
  washerIcon,
  acIcon,
  tvIcon,
  wifiIcon,
  grillIcon,
} from "./assets";
import ImagePicker, {
  Image as CroppedImage,
} from "react-native-image-crop-picker";
import { getStorageData } from "../../../framework/src/Utilities";
import { Alert } from "react-native";
// Customizable Area End

export const configJSON = require("./config");

export interface Props {
  navigation: any;
  id: string;
  // Customizable Area Start
  // Customizable Area End
}

interface S {
  arrayHolder: any;
  token: string;
  // Customizable Area Start
  selectedHomeId: any;
  selectedItemId: any;
  selectedHomeId2: any;
  maxDurationSelectedId: any;
  vin: string;
  timePeriod: any;
  minimumDuration: any;
  maximumDuration: any;
  aboutYourCar: any;
  aboutCar: any;
  spaceTypes: any;
  homeTypes: any;
  mansions: any;
  liscenseNumber: string;
  advNoticeTime: string;
  minTripDur: string;
  maxTripDur: string;
  carDescription: string;
  spaceForGuest: string;
  homeTitle: string;
  homeDescription: string;
  luxgoService: string;
  luxgoTax: string;
  insuranceFee: string;
  amenities: any;
  newHome: string;
  guests: number;
  beds: number;
  bedrooms: number;
  bathrooms: number;
  parkingSpaces: number;
  prevState: string;
  selectedImage: any;
  photoObject: CroppedImage;
  carNameSelect: boolean;
  carName: string;
  odometerSelect: boolean;
  transmissionSelect: boolean;
  trimSelect: boolean;
  styleSelect: boolean;
  odometerName: string;
  transmissionName: string;
  trimName: string;
  styleName: string;
  carFeatures: string[];
  homeAmenities: any;
  validateVin: boolean;
  images: any;
  mainPhoto: any;
  deleteMode: boolean;
  // Customizable Area End
}

interface SS {
  id: any;
}

export default class CatalogueController extends BlockComponent<Props, S, SS> {
  getProductApiCallId: any;
  // Customizable Area Start
  addCarDetailAPICallId: string = "";
  getHomePriceAPICallId: string = "";
  addHomeDetailAPICallId: string = "";
  addHomePricingAPICallId: string = "";
  // Customizable Area End
  constructor(props: Props) {
    super(props);
    this.receive = this.receive.bind(this);

    this.subScribedMessages = [
      getName(MessageEnum.RestAPIResponceMessage),
      getName(MessageEnum.SessionSaveMessage),
      getName(MessageEnum.SessionResponseMessage),
      // Customizable Area Start
      getName(MessageEnum.CatalogueDataMessage),
      getName(MessageEnum.NavigationPayLoadMessage),
      // Customizable Area End
    ];

    this.state = {
      arrayHolder: [],
      token: "",
      // Customizable Area Start
      selectedHomeId: null,
      selectedItemId: null,
      selectedHomeId2: null,
      maxDurationSelectedId: null,
      vin: "",
      liscenseNumber: "",
      advNoticeTime: "",
      minTripDur: "",
      maxTripDur: "",
      carDescription: "",
      spaceForGuest: "",
      homeTitle: "",
      homeDescription: "",
      luxgoService: "0",
      luxgoTax: "0",
      insuranceFee: "0",
      newHome: "",
      guests: 0,
      beds: 0,
      bedrooms: 0,
      parkingSpaces: 0,
      bathrooms: 0,
      selectedImage: null,
      prevState: "",
      photoObject: {
        path: "",
        size: 0,
        width: 0,
        height: 0,
        mime: "",
      },
      carNameSelect: false,
      carName: "",
      odometerSelect: false,
      transmissionSelect: false,
      trimSelect: false,
      styleSelect: false,
      odometerName: "",
      transmissionName: "",
      trimName: "",
      styleName: "",
      carFeatures: [],
      homeAmenities: [],
      images: [],
      mainPhoto: null,
      deleteMode: false,
      timePeriod: [
        {
          id: 1,
          name: "1 hour",
        },
        {
          id: 2,
          name: "2 hours",
        },
        {
          id: 3,
          name: "3 hours",
        },
        {
          id: 4,
          name: "6 hours",
        },
        {
          id: 5,
          name: "12 hours",
        },
        {
          id: 6,
          name: "1 day",
        },
      ],

      minimumDuration: [
        {
          id: 1,
          name: "1 day",
        },
        {
          id: 2,
          name: "2 days",
        },
        {
          id: 3,
          name: "3 days",
        },
        {
          id: 4,
          name: "5 days",
        },
        {
          id: 5,
          name: "2-days min for weekend",
        },
      ],
      maximumDuration: [
        {
          id: 1,
          name: "5 days",
        },
        {
          id: 2,
          name: "2 weeks",
        },
        {
          id: 3,
          name: "1 month",
        },
        {
          id: 4,
          name: "3 months",
        },
        {
          id: 5,
          name: "Any",
        },
      ],
      aboutYourCar: [
        {
          id: 1,
          name: "Lamborghini Urus (2021)",
          sanjay: pencilVector,
        },
        {
          id: 2,
          name: "Odometer",
        },
        {
          id: 3,
          name: "Transmission",
        },
        {
          id: 4,
          name: "Trim (optional)",
        },
        {
          id: 5,
          name: "Style (optional)",
        },
      ],
      aboutCar: [
        {
          id: "1",
          name: "Bluetooth",
          image: bluetooth,
        },
        {
          id: "2",
          name: "Apple CarPlay",
          image: play,
        },
        {
          id: "3",
          name: "Android Auto",
          image: play,
        },
        {
          id: "4",
          name: "Backupcamera",
          image: video,
        },
        {
          id: "5",
          name: "Heated seats",
          image: video,
        },
        {
          id: "6",
          name: "Keyless entry",
          image: video,
        },
        {
          id: "7",
          name: "Blindspot warning",
          image: video,
        },
        {
          id: "8",
          name: "Bike rack",
          image: video,
        },
      ],
      amenities: [
        {
          id: "1",
          animity: "Pool",
          imageIcon: poolIcon,
        },
        {
          id: "2",
          animity: "Hot Tub",
          imageIcon: hotTubIcon,
        },
        {
          id: "3",
          animity: "Patio",
          imageIcon: patioIcon,
        },
        {
          id: "4",
          animity: "Washer / Dryer",
          imageIcon: washerIcon,
        },
        {
          id: "5",
          animity: "Air Conditioning",
          imageIcon: acIcon,
        },
        {
          id: "6",
          animity: "TV",
          imageIcon: tvIcon,
        },
        {
          id: "7",
          animity: "WiFi",
          imageIcon: wifiIcon,
        },
        {
          id: "8",
          animity: "BBQ Grill",
          imageIcon: grillIcon,
        },
      ],
      homeTypes: [
        {
          id: 1,
          name: "Apartment",
        },
        {
          id: 2,
          name: "Residental House",
        },
        {
          id: 3,
          name: "Townhouse",
        },
        {
          id: 4,
          name: "Villa",
        },
        {
          id: 5,
          name: "Guest House",
        },
        {
          id: 6,
          name: "Guest Suite",
        },
      ],
      spaceTypes: [
        {
          id: 1,
          name: "An entire place",
        },
        {
          id: 2,
          name: "A private room",
        },
        {
          id: 3,
          name: "A shared room",
        },
      ],
      mansions: [
        {
          id: "1",
          name: "Luxury Mansion 1",
          price: "$500 / NIGHT",
          distance: "2 mi",
          image: require("../assets/index.jpeg"),
        },
        {
          id: "2",
          name: "Beachfront Villa",
          price: "$750 / NIGHT",
          distance: "1.5 mi",
          image: require("../assets/index.jpeg"),
        },
        {
          id: "3",
          name: "Secluded Estate",
          price: "$1,200 / NIGHT",
          distance: "3 mi",
          image: require("../assets/index.jpeg"),
        },
      ],
      validateVin: true,
      // Customizable Area End
    };
    runEngine.attachBuildingBlock(this as IBlock, this.subScribedMessages);
    // Customizable Area Start
    // Customizable Area End
  }

  async componentDidMount() {
    super.componentDidMount();
    this.getToken();
    if (this.isPlatformWeb() === false) {
      this.props.navigation.addListener("willFocus", () => {
        this.getToken();
      });
    }
    // Customizable Area Start
    this.getUserToken();
    
    // Customizable Area End
  }

  getToken = () => {
    const msg: Message = new Message(
      getName(MessageEnum.SessionRequestMessage)
    );
    this.send(msg);
  };


  getListRequest = (token: any) => {
    const header = {
      "Content-Type": configJSON.productApiContentType,
      token: token,
    };
    const requestMessage = new Message(
      getName(MessageEnum.RestAPIRequestMessage)
    );
    this.getProductApiCallId = requestMessage.messageId;
    requestMessage.addData(
      getName(MessageEnum.RestAPIResponceEndPointMessage),
      configJSON.productAPiEndPoint
    );
    requestMessage.addData(
      getName(MessageEnum.RestAPIRequestHeaderMessage),
      JSON.stringify(header)
    );
    requestMessage.addData(
      getName(MessageEnum.RestAPIRequestMethodMessage),
      configJSON.apiMethodTypeGet
    );
    runEngine.sendMessage(requestMessage.id, requestMessage);
  };

  async receive(from: string, message: Message) {
    // Customizable Area Start
    runEngine.debugLog("Message Recived", message);
    if (getName(MessageEnum.SessionResponseMessage) === message.id) {
      let token = message.getData(getName(MessageEnum.SessionResponseToken));
      this.setState({ token: token });
    }
    if (getName(MessageEnum.NavigationPayLoadMessage) === message.id) {
      const catalogueData = message.getData(
        getName(MessageEnum.CatalogueDataMessage)
      );
      this.handleStates(catalogueData);
    }
    if (getName(MessageEnum.RestAPIResponceMessage) === message.id) {
      const apiRequestCallId = message.getData(
        getName(MessageEnum.RestAPIResponceDataMessage)
      );
      let responseJson = message.getData(
        getName(MessageEnum.RestAPIResponceSuccessMessage)
      );
      if (apiRequestCallId === this.getHomePriceAPICallId && responseJson) {
        this.handleGetHomePriceRes(responseJson.data);
      }
      if (apiRequestCallId === this.addCarDetailAPICallId && responseJson) {
        Alert.alert("Car details added successfully");
      }
      if (apiRequestCallId === this.addHomeDetailAPICallId && responseJson) {
        Alert.alert("Home details added successfully");
      }
      if (apiRequestCallId === this.addHomePricingAPICallId && responseJson) {
        console.log("\nresponse is here \n", JSON.stringify(responseJson));
      }
    }
    // Customizable Area End
  }

  // Customizable Area Start

  getUserToken = async () => {
    let value = await getStorageData("usertoken");
    let tkn = JSON.parse(value);
    this.setState({ token: tkn }, () =>
      console.log("token is get:::", this.state.token)
    );
    this.getHomeTypesApi()
  };



  getHomeTypesApi = async() => {

    console.log("token:::::::::::", this.state.token)

    const header = {
      "Content-Type": configJSON.productApiContentType,
      token: token,
    };
    const requestMessage = new Message(
      getName(MessageEnum.RestAPIRequestMessage)
    );
    this.getProductApiCallId = requestMessage.messageId;
    requestMessage.addData(
      getName(MessageEnum.RestAPIResponceEndPointMessage),
      configJSON.productAPiEndPoint
    );
    requestMessage.addData(
      getName(MessageEnum.RestAPIRequestHeaderMessage),
      JSON.stringify(header)
    );
    requestMessage.addData(
      getName(MessageEnum.RestAPIRequestMethodMessage),
      configJSON.apiMethodTypeGet
    );
    runEngine.sendMessage(requestMessage.id, requestMessage);

  }

  addCarDetail = async () => {
    const carDetailObj = {
      "catalogue[category_id]": "8",
      "catalogue[features][VIN]": this.state.vin,
      "catalogue[features][odometer]": this.state.odometerName,

      "catalogue[features][transmission]": this.state.transmissionName,
      "catalogue[features][trim]": this.state.trimName,
      "catalogue[features][style]": this.state.styleName,

      "catalogue[features][license_plate]": this.state.liscenseNumber,
      "catalogue[features][advances_notice]": this.state.advNoticeTime,
      "catalogue[features][min_trip_duration]": this.state.minTripDur,
      "catalogue[features][max_trip_duration]": this.state.maxTripDur,
      "catalogue[features][car_description]": this.state.carDescription,
      "catalogue[features][car_features][]": this.state.carFeatures,
      "catalogue[images][]": {
        uri: this.state.photoObject?.path,
        type: "image/jpeg",
        name: "image_home",
      } as any,
      "address[country]": "India",
      "address[latitude]": "237782373",
      "address[longitude]": "32323545",
      "address[address]": "32323545",
      "address[pincode]": "73467674",
      "catalogue[name]": "Car",
      "catalogue[car_name]": this.state.carName,
    };

    const formData = this.getFormData(carDetailObj);

    this.addCarDetailAPICallId = await this.apiCall({
      contentType: configJSON.formDataContentType,
      method: configJSON.apiMethodTypePost,
      endPoint: configJSON.carDataApiEndPoint,
      body: formData,
    });
  };

  getHomeTypeId = (item: any) => {
    return item.id;
  };

  getFormData = (object: any) => {
    const formData = new FormData();
    Object.keys(object).forEach((key) => {
      if (Array.isArray(object[key])) {
        object[key].forEach((element: any) => {
          formData.append(key, element);
        });
      } else {
        formData.append(key, object[key]);
      }
    });
    return formData;
  };

  addHomeDetail = async () => {
    const homeDetailObj = {
      "catalogue[category_id]": "9",
      "catalogue[sub_category_id]": "45",
      "catalogue[features][space_type]": this.state.spaceForGuest,
      "catalogue[features][home_title]": this.state.homeTitle,
      "catalogue[features][Guests]": this.state.guests.toString(),
      "catalogue[features][beds]": this.state.beds.toString(),
      "catalogue[features][bathrooms]": this.state.bathrooms.toString(),
      "catalogue[features][Bedrooms]": this.state.bedrooms.toString(),
      "catalogue[features][Parking Spaces]":
        this.state.parkingSpaces.toString(),
      "catalogue[features][home_description]": this.state.homeDescription,
      "address[country]": "India",
      "address[latitude]": "237782373",
      "address[longitude]": "32323545",
      "address[address]": "nrk bizzpark",
      "address[pincode]": "73467674",
      "catalogue[name]": "home",
      "catalogue[features][home_amenities][]": this.state.homeAmenities,
      "catalogue[images][]": this.getFormData({
        uri: this.state.photoObject?.path,
        type: "image/jpeg",
        name: "image_home",
      } as any),
    };

    const formData = this.getFormData(homeDetailObj);

    this.addHomeDetailAPICallId = await this.apiCall({
      contentType: configJSON.formDataContentType,
      method: configJSON.apiMethodTypePost,
      endPoint: configJSON.carDataApiEndPoint,
      body: formData,
    });
  };

  addHomePricing = async () => {
    const pricingObj = {
      "catalogue[earnings]": "2000",
      "catalogue[type]": "Home",
    };
    const formData = this.getFormData(pricingObj);

    this.addHomePricingAPICallId = await this.apiCall({
      contentType: configJSON.formDataContentType,
      method: configJSON.apiMethodTypePost,
      endPoint: configJSON.homeDataApiEndPoint,
      body: formData,
    });
  };

  getHomePrice = async () => {
    this.getHomePriceAPICallId = await this.apiCall({
      contentType: configJSON.productApiContentType,
      method: configJSON.apiMethodTypeGet,
      endPoint: configJSON.getHomePriceApiEndPoint,
    });
  };

  goBack = () => {
    this.props.navigation.goBack();
  };

  navigateTo = (title: string, data: any) => {
    const message = new Message(getName(MessageEnum.NavigationMessage));
    message.addData(getName(MessageEnum.NavigationTargetMessage), title);
    message.addData(getName(MessageEnum.NavigationPropsMessage), this.props);

    const raiseMessage: Message = new Message(
      getName(MessageEnum.NavigationPayLoadMessage)
    );
    raiseMessage.addData(getName(MessageEnum.CatalogueDataMessage), data);
    message.addData(getName(MessageEnum.NavigationRaiseMessage), raiseMessage);

    this.send(message);
  };

  checkValidation = () => {
    if (this.state.vin !== "" || this.state.vin.length < 10) {
      this.setState({ validateVin: false });
    }
  };

  apiCall = async (data: any) => {
    const { contentType, method, endPoint, body } = data;
    const header = {
      "Content-Type": contentType,
      token: this.state.token,
    };
    const requestMessage = new Message(
      getName(MessageEnum.RestAPIRequestMessage)
    );
    requestMessage.addData(
      getName(MessageEnum.RestAPIRequestHeaderMessage),
      JSON.stringify(header)
    );
    requestMessage.addData(
      getName(MessageEnum.RestAPIResponceEndPointMessage),
      endPoint
    );
    requestMessage.addData(
      getName(MessageEnum.RestAPIRequestMethodMessage),
      method
    );
    body &&
      requestMessage.addData(
        getName(MessageEnum.RestAPIRequestBodyMessage),
        body
      );
    runEngine.sendMessage(requestMessage.id, requestMessage);
    return requestMessage.messageId;
  };

  setVin(text: string) {
    this.setState({ vin: text });
  }
  setLiscenseNumber(text: string) {
    this.setState({ liscenseNumber: text });
  }
  setCarDescription(text: string) {
    this.setState({ carDescription: text });
  }
  setHomeTitle(text: string) {
    this.setState({ homeTitle: text });
  }
  setHomeDescription(text: string) {
    this.setState({ homeDescription: text });
  }

  handleDecrement = (key: keyof S) => {
    this.setState((prevState: Readonly<S>) => ({
      ...prevState,
      [key]: prevState[key] - 1,
    }));
  };

  handleIncrement = (key: keyof S) => {
    this.setState(
      (prevState: Readonly<S>): S => ({
        ...prevState,
        [key]: prevState[key] + 1,
      })
    );
  };
  handleGetHomePriceRes = (response: any) => {
    const data = response[0]?.attributes;
    const luxgoSer = data?.luxgo_service;
    const inseFee = data.insurance_fee;
    const tax = data?.rate;

    this.setState({
      luxgoService: luxgoSer,
      insuranceFee: inseFee,
      luxgoTax: tax,
    });
  };

  openCamera = async (title: string) => {
    const pickedImage: CroppedImage = await ImagePicker.openCamera({
      multiple: false,
      mediaType: "photo",
      compressImageQuality: 0.3,
      includeBase64: true,
      cropping: true,
    });
    title === "home"
      ? this.setState({ photoObject: pickedImage }, this.navigateHomePhoto)
      : this.setState({ photoObject: pickedImage }, this.navigateCarPhoto);
  };

  openGallary = async (title: string) => {
    const pickedImage = await ImagePicker.openPicker({
      mediaType: "photo",
      compressImageQuality: 0.3,
      includeBase64: true,
      cropping: true,
      multiple: true,
      maxFiles: title === "car" ? 9 - this.state.images?.length : 1,
    });
    if (title === "car") {
      this.setState(
        {
          images: pickedImage,
        },
        () => {
          this.navigateCarPhoto();
        }
      );
    }
    title === "home" &&
      this.setState({ photoObject: pickedImage[0] }, this.navigateHomePhoto);
  };

  navigateHomePhoto = () => {
    this.navigateTo("HomePhotosStep2", {
      newHome: this.state.newHome,
      spaceTypes: this.state.spaceTypes,
      guests: this.state.guests,
      beds: this.state.beds,
      bedrooms: this.state.bedrooms,
      parkingSpaces: this.state.parkingSpaces,
      bathrooms: this.state.bathrooms,
      homeAmenities: [...this.state.homeAmenities],
      photoObject: this.state.photoObject,
    });
  };

  navigateCarPhoto = () => {
    this.navigateTo("CarPhotosStep2", {
      vin: this.state.vin,
      carName: this.state.carName,
      odometerName: this.state.odometerName,
      transmissionName: this.state.transmissionName,
      trimName: this.state.trimName,
      styleName: this.state.styleName,
      liscenseNumber: this.state.liscenseNumber,
      advNoticeTime: this.state.advNoticeTime,
      minTripDur: this.state.minTripDur,
      maxTripDur: this.state.maxTripDur,
      carDescription: this.state.carDescription,
      carFeatures: [...this.state.carFeatures],
      photoObject: this.state.photoObject,
      images: this.state.images,
    });
  };

  getImageId = (image: any) => {
    return image.path;
  };

  openImagePicker = async () => {
    try {
      const pickedImages = await ImagePicker.openPicker({
        multiple: true,
        mediaType: "photo",
        maxFiles: 9 - this.state.images.length,
      });

      this.setState((prevState) => ({
        images: [
          ...prevState.images,
          ...pickedImages.slice(0, 9 - prevState.images.length),
        ],
      }));
    } catch (error) {
      console.error(error);
    }
  };

  removePhoto = (index: number) => {
    const updatedImages = [...this.state.images];
    updatedImages.splice(index, 1);
    this.setState({ images: updatedImages, deleteMode: false });
  };

  toggleDeleteMode = () => {
    this.setState((prevState) => ({
      deleteMode: !prevState.deleteMode,
    }));
  };

  onPressPhoto = (index: number) => {
    if (this.state.deleteMode) {
      this.removePhoto(index);
    } else {
      this.setMainPhoto(index);
    }
  };

  handleKeyboard = () => {
    this.hideKeyboard();
  };

  handleStates = (catalogueData: any) => {
    this.setState({
      vin: catalogueData.vin,
      carName: catalogueData.carName,
      odometerName: catalogueData.odometerName,
      transmissionName: catalogueData.transmissionName,
      trimName: catalogueData.trimName,
      styleName: catalogueData.styleName,
      liscenseNumber: catalogueData.liscenseNumber,
      advNoticeTime: catalogueData.advNoticeTime,
      minTripDur: catalogueData.minTripDur,
      maxTripDur: catalogueData.maxTripDur,
      carDescription: catalogueData.carDescription,
      carFeatures: catalogueData.carFeatures
        ? catalogueData.carFeatures
        : this.state.carFeatures,
      images: catalogueData.images ?? [],
    });
    this.setState({
      newHome: catalogueData.newHome,
      spaceForGuest: catalogueData.spaceForGuest,
      guests: catalogueData.guests ? catalogueData.guests : this.state.guests,
      beds: catalogueData.beds ? catalogueData.beds : this.state.beds,
      bedrooms: catalogueData.bedrooms
        ? catalogueData.bedrooms
        : this.state.bedrooms,
      bathrooms: catalogueData.bathrooms
        ? catalogueData.bathrooms
        : this.state.bathrooms,
      parkingSpaces: catalogueData.parkingSpaces
        ? catalogueData.parkingSpaces
        : this.state.parkingSpaces,
      homeAmenities: catalogueData.homeAmenities
        ? catalogueData.homeAmenities
        : this.state.homeAmenities,
      photoObject: catalogueData.photoObject
        ? catalogueData.photoObject
        : this.state.photoObject,
    });
  };

  setMainPhoto = (index: number) => {
    this.setState({ mainPhoto: this.state.images[index] });
  };

  // Customizable Area End
}
Leave a Comment