// 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_hue extends cc.Component {

    cp_palette: cp_palette = null;

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

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

    h: number = 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));

        let { h, s, v } = this.cp_palette.get_hsv();
        this.h = pos_event.y / ui.height;
        this.cp_palette.set_hsv(this.h, s, v);
        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);

        let { h, s, v } = this.cp_palette.get_hsv();
        this.h = y;
        this.cp_palette.set_hsv(this.h, s, v);
        this.cp_palette.update_all();
    }

    update_sprite() {
        let grid = [];
        let len = this.cp_palette.density;
        let h = 0;   // 0 - 360 色相（H）是色彩的基本属性，就是平常所说的颜色名称，如红色、黄色等。
        let s = 1; // 0 - 100 饱和度（S）是指色彩的纯度，越高色彩越纯，低则逐渐变灰，取0-100%的数值。
        let v = 1;   // 0 - 100 明度（V），亮度（L），取0-100%。
        let dif = 1 / len;

        for (let y = 0; y < len; y++) {
            //宽度为1
            grid[y] = [cp_palette_util.get_rgba_arr(h, s, v)];
            h += dif;
        }
        // console.log(grid);
        this.sprite.spriteFrame = cp_palette_util.grid2SpriteFrame(grid, 1, this.cp_palette.density);
    }

    update_cursor() {
        let h = this.h;
        if (h == null) {
            h = this.cp_palette.get_hsv().h;
        }
        if (h == 0) {
            return;
        }

        this.h = null;
        const ui = this.node.getComponent(cc.UITransform);
        this.cursor.setPosition(this.cursor.getPosition().x, ui.height * h);
        // console.log("hub", y, h, s, v);
    }
}
