import { storeToRefs } from 'pinia'
import { useSlidesStore } from '@/store'
import { ResolveFonts } from './font';
import type { PPTElement, Slide } from '@/types/slides'
import { compressionThumbnail, cropImage } from "./compressor"
import { ResolveLayer } from './layer'
import { ResolveText } from './text'

let Z_INDEX = 0
export const ResolveThumbHandler = async (psd:any)=>{

    const { _children } = psd.tree()
    let imgs:Array<any> = []
    let imgBase64String = psd.image.toBase64()

    for (let i = 0; i < _children.length; i++) {
        
        Z_INDEX = 2000

        const item = _children[i];
        if(item.layer.artboard && item.layer.visible) {
            let cropImagePath = await cropImage(imgBase64String,"image/jpeg",item.layer.artboard().export().coords)
            let imagePath = await compressionThumbnail(cropImagePath,"image/jpeg",600)
            imgs.push(imagePath)
        }
    }
    
    return imgs
}
export const generateUniqueId = () => {
    const timestamp = new Date().getTime()
    const randomNum = Math.floor(Math.random() * 1000)
    return '-' +timestamp + '-' + randomNum
}
export const ResolvePsdToSliderHandler = async (psd:any) => {
    const { slides } = storeToRefs(useSlidesStore())
    const ID_PREV = "import-slide-"
    let items:Array<any> = psd.tree().children().filter((x:any)=>x.layer.visible)
    let sliders:Array<Slide> = []
    
    if(items && items.length>0){

        for (let i = 0; i < items.length; i++) {
            
            const x = items[i];
            // let t =CreateDefaultSlider(ID_PREV+i)
            // let randomNum  = Math.floor(Math.random()*100)+i
            // let t =CreateDefaultSlider(ID_PREV+randomNum)
            let t =CreateDefaultSlider(ID_PREV+i+generateUniqueId())
            t.isTripItems=x.name.indexOf('trip_item')!=-1
            const {_children} = x

            if(_children && _children.length>0){
                const {top,left} = x.layer.artboard().export().coords
                t.elements = (await GetSlidersHandler(_children,left,top)).reverse()
            }

            sliders.push(t)
        }

    }
    if(slides.value.length>0 && !(slides.value.length==1 && slides.value[0].elements.length==0)){
        let copySlides = JSON.parse(JSON.stringify(slides.value))
        copySlides.splice(slides.value.length,0,...sliders)
        return copySlides
    }else {
        return sliders.filter(x=>x.elements && x.elements.length>0)
    }
}

export const ResolvePsdDrawingBoardSize= async (psd:any) => {
    let items:Array<any> = psd.tree().children().filter((x:any)=>x.layer.visible)
    let DrawingBoardSize = {
        Width: 0,
        Height: 0
    }
    if(items && items.length>0){
        for (let i = 0; i < items.length; i++) {
            const x = items[i];
            const {_children} = x
            if(_children && _children.length>0){
                DrawingBoardSize = {
                    Width: x.layer.artboard().export().coords.right-x.layer.artboard().export().coords.left,
                    Height: x.layer.artboard().export().coords.bottom-x.layer.artboard().export().coords.top
                }
            }

        }
    }
    return DrawingBoardSize
}

export const ResolveSliderFonts = (psd:any) => {

    let items:Array<any> = psd.tree().children().filter((x:any)=>x.layer.visible)
    let fonts:Array<any> = []
    
    if(items && items.length>0){
        fonts = GetFontHandler(items)
    }

    return Array.from(new Set(fonts))
}

const CreateDefaultSlider = (id:string):Slide =>{
    return {
        id,
        pageType:1,
        elements:[],
        background: {
            type: 'solid',
            color: '#ffffff',
        }
    }
}

const GetSlidersHandler = async (child:any[],offsetLeft:number,offsetTop:number,groupId:string ='') : Promise<PPTElement[]> =>{

    let elements = [] as Array<PPTElement>

    for (let i = 0; i < child.length; i++) {
        const x= child[i]
        Z_INDEX--
        if(x.layer.name == 'first_row') groupId='first_row'
        if(x.layer.name == 'form_bg') groupId = ''
        if(x.layer.typeTool){
            elements.push(ResolveText(x, Z_INDEX, offsetLeft, offsetTop,groupId))
        }
        else if(x.width && x.width>0 && x.layer.image){
            
            let ele = await ResolveLayer(x, Z_INDEX, offsetLeft, offsetTop,groupId)
            if(ele) elements.push(ele)
        }
        if(x._children && x._children.length>0){
            let childers = await GetSlidersHandler(x._children,offsetLeft,offsetTop,groupId) ?? []
            elements = elements.concat(childers)
        }
        //groupId=''
    }
    
    return elements
}

const GetFontHandler = (child:any[]) : any[] => {
    let fonts = []
    if(child && child.length>0){

        for (let i = 0; i < child.length; i++) {
            const x = child[i];
            
            if(x.layer.typeTool){
                let temp = ResolveFonts(x)
                if(temp && temp.length>0) fonts.push(...temp)
            }
            if(x._children && x._children.length>0){
                let childers = GetFontHandler(x._children) ?? []
                fonts = fonts.concat(childers)
            }
        }
    }

    return fonts
}
