// 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_hsv } from "./cp_palette";
import cp_palette_util from "./cp_palette_util";

const { ccclass, property } = cc._decorator;

@ccclass
export default class cp_palette_color_alpha extends cc.Component {

    cp_palette: cp_palette = null;

    @property(cc.Sprite)
    sprite: cc.Sprite = null;

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

    protected onLoad(): void {
        this.node.on(cc.Node.EventType.TOUCH_START, this.on_touch_start, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.on_touch_move, this);
    }

    protected onDestroy(): void {
        this.node.targetOff(this);
    }

    on_touch_start(event: cc.EventTouch) {
        const pos_location = event.getUILocation();
        const ui = this.node.getComponent(cc.UITransform);
        let pos_event = ui.convertToNodeSpaceAR(cc.v3(pos_location.x, pos_location.y, 0));

        this.cp_palette.alpha = Math.floor((pos_event.y / ui.height) * 255);

        this.cp_palette.update_all();
    }

    on_touch_move(event: cc.EventTouch) {
        const pos = this.cursor.getPosition();
        const ui = this.node.getComponent(cc.UITransform);
        let y = (pos.y + event.getDeltaY()) / ui.height;
        y = Math.max(0, y);
        y = Math.min(y, 1);

        this.cp_palette.alpha = Math.floor(y * 255);
        this.cp_palette.update_all();
    }

    update_sprite() {
        let grid = [];
        const { h, s, v } = this.cp_palette.get_hsv();
        let len = Math.min(this.cp_palette.density, 255);
        for (let y = 0; y < len; y++) {
            //宽度为1
            const a = (y / (len - 1)) * 255;
            grid[y] = [cp_palette_util.get_rgba_arr(h, s, v, a)];
        }
        // console.log(grid);
        this.sprite.spriteFrame = cp_palette_util.grid2SpriteFrame(grid, 1, len);
    }

    update_cursor() {
        const alpha = this.cp_palette.alpha;

        let y = alpha / 255;

        const ui = this.node.getComponent(cc.UITransform);
        this.cursor.setPosition(this.cursor.getPosition().x, ui.height * y);

        // console.log("alpha", y);
    }

}
