import * as React from 'react';
import { View } from 'react-native';
import Identicon from 'identicon.js';
import { SvgXml } from 'react-native-svg';

import Base64Utils from './../utils/Base64Utils';
import PrivacyUtils from './../utils/PrivacyUtils';

const hash = require('object-hash');

const IDENTICON_TITLE_MAX_LENGTH = 24;

export const NodeTitle = (selectedNode: any, overrideSensitivity = false) => {
    const displayName =
        selectedNode && selectedNode.nickname
            ? selectedNode.nickname
            : selectedNode && selectedNode.implementation === 'lndhub'
            ? selectedNode.lndhubUrl
                  .replace('https://', '')
                  .replace('http://', '')
            : selectedNode && selectedNode.url
            ? selectedNode.url.replace('https://', '').replace('http://', '')
            : selectedNode && selectedNode.port
            ? `${selectedNode.host}:${selectedNode.port}`
            : (selectedNode && selectedNode.host) || 'Unknown';

    return overrideSensitivity
        ? displayName
        : PrivacyUtils.sensitiveValue({ input: displayName, fixedLength: 8 });
};

export default function NodeIdenticon({
    selectedNode,
    width,
    rounded
}: {
    selectedNode: any;
    width?: number;
    rounded?: boolean;
}) {
    const fullTitle = NodeTitle(selectedNode, true);
    const title =
        fullTitle.length > IDENTICON_TITLE_MAX_LENGTH
            ? fullTitle.substring(0, IDENTICON_TITLE_MAX_LENGTH - 3) + '...'
            : fullTitle;

    const data = new Identicon(
        hash.sha1(
            selectedNode && selectedNode.implementation === 'lndhub'
                ? `${title}-${selectedNode.username}`
                : selectedNode &&
                  selectedNode.implementation === 'nostr-wallet-connect'
                ? `${title}-${selectedNode.nostrWalletConnectUrl}`
                : selectedNode && selectedNode.implementation === 'embedded-lnd'
                ? `${title}-${selectedNode.lndDir || 'lnd'}`
                : title
        ),
        // @ts-ignore:next-line
        {
            background: [255, 255, 255, 255],
            size: width,
            format: 'svg'
        }
    ).toString();

    return (
        <View style={{ borderRadius: rounded ? width : 0, overflow: 'hidden' }}>
            <SvgXml xml={Base64Utils.base64ToUtf8(data)} />
        </View>
    );
}
