import * as React from 'react';
import superagent from 'superagent';


import * as CSS from 'csstype';
import './index.less';
interface CSSProperties extends CSS.Properties<string | number> {
    /**
     * The index signature was removed to enable closed typing for style
     * using CSSType. You're able to use type assertion or module augmentation
     * to add properties or an index signature of your own.
     *
     * For examples and more information, visit:
     * https://github.com/frenic/csstype#what-should-i-do-when-i-get-type-errors
     */
}
export interface IIconProps {
    src: string;
    width?: number;
    height?: number;
    color?: string;
    className?: string;
    style?: CSSProperties;
}

export default function Icon(props: IIconProps) {

    const classNameHandle = () => {
        return props.className ? `icon ${props.className}` : 'icon';
    };

    const [htmlString, setHtmlString] = React.useState('');

    const anticonRef: any = React.useRef();

    React.useEffect(() => {
        superagent.get(props.src).end((err, res) => {
            if (!err) {
                setHtmlString(res.text);
            }
        });
    }, []);

    // 去掉 svg 里的 title
    React.useEffect(() => {
        const div: any = anticonRef.current;
        const svg = div.querySelector('svg');
        const img = div.querySelector('image');
        const path = div.querySelectorAll('path') || [];
        if (!svg) {
            return;
        }
        props.width && svg.setAttribute('width', props.width + '');
        props.height && svg.setAttribute('height', props.height + '');
        if (img) {
            img.setAttribute('width', '100%');
            img.setAttribute('height', '100%');
        }
        
        const title = div.querySelector('title');
        if (title) {
            title.innerHTML = '';
        }
        
        const defs = div.querySelector('defs');
        if (defs) {
            defs.innerHTML = '';
        }
        
        if (path && path.length && props.color) {
            Array.prototype.slice.apply(path).map((el) => {
                el.setAttribute('fill', props.color);
            })
        }
    }, [htmlString, props.color]);


    return (
        <i ref={anticonRef} className={`anticon ${classNameHandle()}`} style={{verticalAlign: 'middle', ...props.style}} dangerouslySetInnerHTML={{ __html: htmlString }} />
    );
}