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

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

const { ccclass, property } = cc._decorator;
enum cp_palette_enum_rgba {
    R,
    G,
    B,
    A,
}
@ccclass
export default class cp_palette_slider extends cc.Component {

    @property(cc.Slider)
    slider: cc.Slider = null;

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

    @property({
        type: cc.Enum(cp_palette_enum_rgba)
    })
    type: cp_palette_enum_rgba = cp_palette_enum_rgba.R;

    cp_palette: cp_palette = null;

    init() {

    }

    on_change_slider(slider: cc.Slider): void {
        if (this.edit_box) {
            this.edit_box.string = Math.floor((slider.progress * 255)) + "";
            this._update_value();
        }
    }

    on_change_edit_box(edit_box: cc.EditBox) {
        this._update_slider();
        this._update_value();
    }

    private _update_slider() {
        if (this.slider) {
            let value = Number(this.edit_box.string);
            value = Math.min(value, 255);
            value = Math.max(value, 0);
            this.slider.progress = value / 255;
        }
    }

    private _update_value() {
        let value = Number(this.edit_box.string);

        switch (this.type) {
            case cp_palette_enum_rgba.R:
                this.cp_palette.set_r(value);
                break;
            case cp_palette_enum_rgba.G:
                this.cp_palette.set_g(value);
                break;
            case cp_palette_enum_rgba.B:
                this.cp_palette.set_b(value);
                break;
            case cp_palette_enum_rgba.A:
                this.cp_palette.alpha = value;
                break;
        }
        this.cp_palette.update_all();
    }

    update_cursor() {
        let value = 0;
        let color = this.cp_palette.color;
        switch (this.type) {
            case cp_palette_enum_rgba.R:
                value = color.r;
                break;
            case cp_palette_enum_rgba.G:
                value = color.g;
                break;
            case cp_palette_enum_rgba.B:
                value = color.b;
                break;
            case cp_palette_enum_rgba.A:
                value = this.cp_palette.alpha;
                break;
        }
        this.edit_box.string = value + "";
        this._update_slider();
    }

}
