Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
6.0 kB
2
Indexable
Never
import React, { memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { CommonActions, useFocusEffect, useNavigation, useNavigationState, useRoute } from '@react-navigation/native';
import { LoaderScreen } from 'react-native-ui-lib';
import _ from 'lodash';
import { StyleSheet } from 'react-native';

import { BaseScreen, BuySellButtons } from '../../components/ui';
import { Tabbar } from '../../components/business';
import {
  PriceLevelScreen,
  FundamentalScreen,
  DepthScreen,
  SummaryScreen,
  OrderBookScreen,
  CustodianAnalysisScreen,
  BrokerIdScreen,
} from './symbolDetailTabs';
import { GetCompanyProfile, GetGraphData, GetUserLicense } from '../../api/matriks';
import { useColors } from '../../hooks';
import { Matriks } from '../../components/Matriks';
import { formattedByLanguage } from '../../utils/formatCurrency';
import { getLicense } from '../../utils/license';

export const MarketSymbolDetail = memo(() => {
  const {
    params: { symbolCode },
  }: any = useRoute();
  const { t, i18n } = useTranslation();

  const navigation = useNavigation();

  const currentScreen = useNavigationState(state => state.routes[0].name);

  const [symbolData, setSymbolData] = useState();
  const [activeBottomTabIndex, setActiveBottomTabIndex] = useState<number>(0);
  const { colors } = useColors();
  const [selectedTab, setSelectedTab] = useState(0);
  const [tabData, setTabData] = useState([]);

  const { data: userLicense, isLoading: isUserLicenseLoading } = GetUserLicense();
  const { data: companyProfile, isLoading: isCompanyProfileLoading } = GetCompanyProfile(symbolCode);
  const { data: graphData, isLoading: isGraphDataLoading } = GetGraphData(symbolCode, activeBottomTabIndex);

  useFocusEffect(
    useCallback(() => {
      if (symbolCode) {
        subscribeSymbolDetail();
      }
      return () => {
        // VIEWABLE_ITEMS = [];
        console.log('UNSUBSCRIBE!!!!!');
        Matriks.unsubscribeDetail();
      };
    }, [symbolCode]),
  );

  const subscribeSymbolDetail = async () => {
    try {
      await Matriks.subscribeSymbolDetail(
        [symbolCode],
        (response: any) => {
          if (response?.symbolCode === symbolCode) {
            setSymbolData(response);
          }
        },
        [],
      );
    } catch (error) {
      console.log('subscribeSymbolDetail Error', error);
    }
  };

  useEffect(() => {
    if (!_.isNil(symbolData)) {
      const tabs = [{ label: t('summary') }];

      if (symbolData.exchangeId === 4) {
        tabs.push({ label: t('depth') }, { label: t('priceLevel') }, { label: t('brokerId') });
        if (symbolData.symbolType === 'S') {
          tabs.push({ label: t('orderBook') }, { label: t('fundamentals') }, { label: t('custodianAnalysis') });
        } else {
          tabs.push({ label: t('orderBook') });
        }
      } else if (symbolData.exchangeId === 9) {
        tabs.push({ label: t('depth') }, { label: t('priceLevel') }, { label: t('brokerId') });
      }

      setTabData(tabs);
    }
  }, [symbolData]);

  function licenseControlForBrokerId() {
    const exchangeId = symbolData?.exchangeId;
    const licenseType = exchangeId === 4 ? ['AKD', 'AKDE'] : exchangeId === 9 ? ['VAKD'] : [];

    return hasLicense(licenseType);
  }

  function hasLicense(licenseType) {
    const response = getLicense(userLicense, licenseType);
    return response;
  }

  const renderTabContent = () => {
    switch (selectedTab) {
      case 0:
        return (
          <SummaryScreen
            symbolData={symbolData}
            companyProfile={companyProfile}
            isCompanyProfileLoading={isCompanyProfileLoading}
            graphData={graphData}
            isGraphDataLoading={isGraphDataLoading}
            setActiveBottomTabIndex={index => setActiveBottomTabIndex(index)}
            activeBottomTabIndex={activeBottomTabIndex}
            symbolCode={symbolCode}
          />
        );
      case 1:
        return <DepthScreen symbolCode={symbolCode} license={hasLicense(['PD2P'])} />;
      case 2:
        return <PriceLevelScreen symbolCode={symbolCode} />;
      case 3:
        return <BrokerIdScreen symbolData={symbolData} symbolCode={symbolCode} license={licenseControlForBrokerId()} />;
      case 4:
        return <OrderBookScreen symbolCode={symbolCode} license={hasLicense(['PD2P'])} />;
      case 5:
        return (
          <FundamentalScreen
            symbolCode={symbolCode}
            symbolDescription={symbolData?.symbolDesc}
            price={symbolData?.last}
          />
        );
      case 6:
        return (
          <CustodianAnalysisScreen
            symbolCode={symbolCode}
            symbolDescription={symbolData?.symbolDesc}
            price={symbolData?.last}
          />
        );
      default:
        return null;
    }
  };
  const backAction = () => {
    if (currentScreen !== 'marketHome') {
      navigation.dispatch(
        CommonActions.reset({
          index: 0,
          routes: [{ name: 'marketHome' }],
        }),
      );
    }
    navigation.goBack();
  };

  return (
    <BaseScreen
      header={{
        type: 'symbolHeader',
        symbolCode,
        symbolDescription: symbolData?.symbolDesc,
        price: symbolData?.last ? formattedByLanguage(i18n, symbolData?.last, symbolData?.fractionCount) : '',
        backAction,
      }}>
      {tabData.length > 0 ? (
        <>
          <Tabbar
            itemStyle={styles.tabBarItem}
            data={tabData}
            setSelectedTab={setSelectedTab}
            selectedTab={selectedTab}
          />
          {renderTabContent()}
          <BuySellButtons symbolCode={symbolCode} symbolData={symbolData} />
        </>
      ) : (
        <LoaderScreen color={colors.action} overlay size="large" />
      )}
    </BaseScreen>
  );
});

const styles = StyleSheet.create({
  tabBarItem: {
    paddingHorizontal: 24,
  },
});