import { _decorator, AudioClip, AudioSource, Component, Label, Node, Vec3 } from 'cc';
import { att_text_sound_data, event_item } from '../../../data/data';
import { gameManager } from '../gameManager';
import { ClientEvent } from '../../clientEvent';
import { config } from '../../config';
const { ccclass, property } = _decorator;

@ccclass('sound_text_content')
export class sound_text_content extends Component {

    @property(Node) lab_text:Node = null;
    @property(Node) item_node:Node = null;
    private m_audio_clip:AudioClip = null;
    private mData:att_text_sound_data = null;
    private mWidgetId:number = 0;
    protected start(): void {
        this.node.addComponent(AudioSource)
    }
    public isCanClose(){
        if(this.mData.is_open_click_close==undefined){
            this.mData.is_open_click_close = true;
            return true;
        }
        return this.mData.is_open_click_close;
    }
    public show(widget_id,data:att_text_sound_data,ac:AudioClip){
        this.node.on(Node.EventType.TOUCH_START,()=>{
            if(this.isCanClose()){
                this.node.off(Node.EventType.TOUCH_START)
                this.onAudioEnded()
            }
        })
        this.mWidgetId = widget_id;
        this.mData = data;
        this.m_audio_clip = ac;
        this.lab_text.getComponent(Label).string = this.mData.text;
        this.item_node.position = new Vec3(this.item_node.position.x,this.mData.pos_y)
        if(gameManager.Singleton.getLevelData()){
            if(gameManager.getUserData().isOpenPeiYin){
                this.onPlaySound()
            }
        }else{
            this.onPlaySound()
        }
   
    }

    getAudioSource(){
        if(this.node.getComponent(AudioSource)==null){
            this.node.addComponent(AudioSource)
        }
        return this.node.getComponent(AudioSource)
    }

    onPlaySound(){
        this.getAudioSource().stop()
        this.node.off(AudioSource.EventType.STARTED);
        this.node.off(AudioSource.EventType.ENDED);
        this.node.on(AudioSource.EventType.STARTED, this.onAudioStarted, this);
        // Register the ended event callback
        this.node.on(AudioSource.EventType.ENDED, this.onAudioEnded, this);

        if (this.m_audio_clip instanceof AudioClip) {
            this.getAudioSource().clip = this.m_audio_clip;
            this.getAudioSource().play();
            this.getAudioSource().volume = 1;
        }

    }

    
    onAudioStarted(){

    }

    onAudioEnded(){
        this.node.off(AudioSource.EventType.STARTED);
        this.node.off(AudioSource.EventType.ENDED);
        this.node.active = false;
        ClientEvent.dispatchEvent(config.EventRun.WIDGET_FINISH,this.mWidgetId)
    }
}


