import { _decorator, Component, Node, Size, SpringJoint2D, Sprite, SpriteFrame, UITransform } from 'cc';
import { base_ui } from '../fw/base_ui';
import { tools } from '../tools';
import { http } from '../http';
import { config } from '../config';
import { GameManager } from '../GameManager';
import { ClientEvent } from '../lib/clientEvent';
const { ccclass, property } = _decorator;

@ccclass('announcement')
export class announcement extends base_ui {
    @property(Node) btn_close:Node = null
    @property(Node) empty:Node = null
    @property(Node) content_img:Node = null

    protected start(): void {
        this.onButtonListen(this.btn_close, ()=>{
            this.close()
        })

        GameManager.requestDelay(()=>{
            this.requestBulletin()
        })
    }

    private requestBulletin() {
        http.get(config.STATIC_API.bulletin, (err,d)=>{
            if(!err){
                let data = JSON.parse(d)
                if(data.code===config.status.SUCCESS){
                    let img_url = data.content.img_url
                    if(img_url.length<=0) {
                        this.empty.active = true
                    } else {
                        tools.loadRemoteImg(img_url, (r)=>{
                            this.showContentImg(r.sf)
                        })
                        this.setRead()
                    }
                }
            } else{
                console.log("err bulletin",err)
            }
        })
    }

    private showContentImg(sf:SpriteFrame) {
        if(sf==null||sf==undefined) {
            this.empty.active = true
            return
        }
        this.empty.active = false
        let img_width = this.content_img.getComponent(UITransform).contentSize.width
        let bili = sf.width / sf.height
        let img_height = img_width / bili
        let img_size = new Size(img_width, img_height)
        this.content_img.getComponent(UITransform).setContentSize(img_size)
        this.content_img.getComponent(Sprite).spriteFrame = sf
    }

    private setRead() {
        if(tools.user_red_dot_data.bulletin_red_dot==0) {
            return
        }
        GameManager.requestUserSetReadRedDot(config.RED_DOT_TYPE.announcement, ()=>{
            tools.user_red_dot_data.bulletin_red_dot = 0
            ClientEvent.dispatchEvent(config.UI_EVENT.UPDATE_ANNOUNCEMENT_RED_DOT_STATUS)
        })
    }
}

