// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import * as cc from "cc";
import cp_palette, { cp_palette_options } from "./cp_palette";

const { ccclass, property } = cc._decorator;

@ccclass
export default class cp_palette_preview extends cc.Component {

    cp_palette: cp_palette = null;

    @property(cc.Node)
    in_node: cc.Node = null;

    @property(cc.Node)
    out_node: cc.Node = null;

    @property(cc.EditBox)
    out_editor: cc.EditBox = null;

    init(options: cp_palette_options) {
        this.in_node.getComponent(cc.Sprite).color = options.color.clone();
        this.in_node.getComponent(cc.UIOpacity).opacity = options.alpha;
    }

    on_change_edit_box() {
        try {
            if (this.out_editor.string.length < 7) {
                return;
            }
            let color = new cc.Color().fromHEX(this.out_editor.string + "FF");
            this.cp_palette.set_color(color);
            this.cp_palette.update_all();
        } catch (error) {
            console.log(error.message);
        }
    }

    update_sprite() {
        this.out_node.getComponent(cc.Sprite).color = this.cp_palette.color;
        this.out_node.getComponent(cc.UIOpacity).opacity = this.cp_palette.alpha;
        this.out_editor.string = "#" + this.cp_palette.color.toHEX().toUpperCase();
    }
}
