import { _decorator, Component, Label, Node, Sprite } from 'cc';
import { base_ui } from '../../fw/base_ui';
import { car_lib_top } from './car_lib_top';
import { car_lib_bottom } from './car_lib_bottom';
import { car_lib_list_item } from './car_lib_list_item';
import { userDataManager } from '../../manager/userDataManager';
import { ClientEvent } from '../../lib/clientEvent';
import { config } from '../../config';
import { http } from '../../http';
const { ccclass, property } = _decorator;

@ccclass('car_lib')
export class car_lib extends base_ui {
    @property(Node) btn_back:Node = null
    @property(Node) top_node:Node = null
    @property(Node) bottom_node:Node = null

    private m_cur_car:car_lib_list_item = null
    
    start() {
        this.onButtonListen(this.btn_back, ()=>{
            this.syncUserSetDefaultCar()
            this.close()
        })

        this.initData()
    }

    initData() {
        this.top_node.getComponent(car_lib_top).init()
        this.bottom_node.getComponent(car_lib_bottom).init(this.onClickListItem.bind(this))
    }

    private onClickListItem(item:car_lib_list_item) {
        this.m_cur_car = item
        userDataManager.user_car_list.default_car_id = item.getData().id
        this.top_node.getComponent(car_lib_top).reloadUserCar()
        ClientEvent.dispatchEvent(config.UI_EVENT.UPDATE_USER_DEFAULT_CAR)
    }

    private syncUserSetDefaultCar() {
        if(this.m_cur_car==null) {
            return
        }
        let opt = {'car_id': this.m_cur_car.getData().id}
        http.post(config.API.user_set_default_car_id, opt, (err,d)=>{
            if(!err) {
                let nd = JSON.parse(d)
                if(nd.code === config.status.SUCCESS){}  
            }
        })
    }

    public initGameShowStatus(parent:Node){
        this.bottom_node.getComponent(car_lib_bottom).initGameStatusParent(parent)
    }
}

