import { DrawOptions } from "../types"
import { getTextFromHtml } from "./Dom"
import { checkClipboardReadEnable } from "./Platform"
import { htmlEscape } from "./String"

// 将数据设置到用户剪切板中
export const setDataToClipboard = (data: any): void => {
    if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(JSON.stringify(data))
    }
}

// 从用户剪贴板中读取文字和图片
export const getDataFromClipboard = async (): Promise<{
    text: string | null,
    img: Blob | null
}> => {
    let text: string | null = null
    let img: Blob | null = null
    if (checkClipboardReadEnable()) {
        const items = await navigator.clipboard.read()
        if (items && items.length > 0) {
            for (const clipboardItem of items) {
                for (const type of clipboardItem.types) {
                    if (/^image\//.test(type)) {
                        img = await clipboardItem.getType(type)
                    } else if (type === 'text/plain') {
                        const blob = await clipboardItem.getType(type)
                        text = await blob.text()
                    }
                }
            }
        }
    }
    return {
        text,
        img
    }
}

export const exitFullscreen = (): void => {
    if (!document.fullscreenElement) return;
    if (document.exitFullscreen) {
        document.exitFullscreen();
    } else if ((document as any).webkitExitFullscreen) {
        (document as any).webkitExitFullscreen();
    } else if ((document as any).mozCancelFullScreen) {
        (document as any).mozCancelFullScreen();
    }
};

// 全屏事件检测
const getOnfullscreenEvent = (): string | undefined => {
    if ((document.documentElement as any).requestFullscreen) {
        return 'fullscreenchange';
    } else if ((document.documentElement as any).webkitRequestFullscreen) {
        return 'webkitfullscreenchange';
    } else if ((document.documentElement as any).mozRequestFullScreen) {
        return 'mozfullscreenchange';
    } else if ((document.documentElement as any).msRequestFullscreen) {
        return 'msfullscreenchange';
    }
    return undefined;
};

export const fullscreenEvent = getOnfullscreenEvent();

// 全屏
export const fullScreen = (element: Element): void => {
    if (element.requestFullscreen) {
        element.requestFullscreen();
    } else if ((element as any).webkitRequestFullscreen) {
        (element as any).webkitRequestFullscreen();
    } else if ((element as any).mozRequestFullScreen) {
        (element as any).mozRequestFullScreen();
    }
};

interface SmmData {
    simpleMindMap: boolean
    data: any
}

// 创建smm粘贴的粘贴数据
export const createSmmFormatData = (data: any): SmmData => {
    return {
        simpleMindMap: true,
        data
    }
}

// 检查是否是smm粘贴格式的数据
export const checkSmmFormatData = (data: any): {
    isSmm: boolean,
    data: any
} => {
    let smmData: any = null
    // 如果是字符串，则尝试解析为对象
    if (typeof data === 'string') {
        try {
            const parsedData = JSON.parse(data)
            // 判断是否是对象，且存在属性标志
            if (typeof parsedData === 'object' && parsedData.simpleMindMap) {
                smmData = parsedData.data
            }
        } catch (error) { }
    } else if (typeof data === 'object' && data.simpleMindMap) {
        // 否则如果是对象，则检查属性标志
        smmData = data.data
    }
    const isSmm = !!smmData
    return {
        isSmm,
        data: isSmm ? smmData : String(data)
    }
}

// 处理输入框的粘贴事件，会去除文本的html格式、换行
export const handleInputPasteText = (e: ClipboardEvent, text?: string): void => {
    e.preventDefault()
    const selection = window.getSelection()
    if (!selection?.rangeCount) return
    selection.deleteFromDocument()
    text = text || e.clipboardData?.getData('text')
    // 转义特殊字符
    text = htmlEscape(text)
    // 去除格式
    text = getTextFromHtml(text)
    const textArr = text.split(/\n/g)
    const fragment = document.createDocumentFragment()
    textArr.forEach((item, index) => {
        const node = document.createTextNode(item)
        fragment.appendChild(node)
        if (index < textArr.length - 1) {
            const br = document.createElement('br')
            fragment.appendChild(br)
        }
    })
    selection.getRangeAt(0).insertNode(fragment)
    selection.collapseToEnd()
}


export const drawImage = (
    ctx: CanvasRenderingContext2D,
    image: CanvasImageSource,
    drawOpt: DrawOptions
): void => {
    ctx.drawImage(
        image,
        drawOpt.sx,
        drawOpt.sy,
        drawOpt.swidth,
        drawOpt.sheight,
        drawOpt.x,
        drawOpt.y,
        drawOpt.width,
        drawOpt.height
    )
}