
import { actionAddins } from ".";
import $ from 'jquery';
import { IAction, IActionProperty, IActionNode, IActionResult } from "../types/ActionTypes";
import "./button-add.css";

/**
 * ボタン配置属性定義
 */
interface IButtonAddProps {
    //ボタン表示名
    buttonName: string;
    //配置位置
    position: string;
    //イベント名
    eventName:string
}   

export class ButtonAddAction implements IAction {
    name: string; 
    actionProps: IActionProperty[]; 
    props: IButtonAddProps;
    constructor() { 
        this.name = "ボタンの配置";
        this.actionProps = [];
        this.props = {
            buttonName: '',
            position: '',
            eventName:''
        }
        this.register();
    }

    /**
     * アクションの実行を呼び出す
     * @param actionNode 
     * @param event 
     * @returns 
     */
    async process(actionNode: IActionNode, event: any): Promise<IActionResult> { 
        let result = { 
            canNext: true,
            result: false
        };
        try { 
            this.actionProps = actionNode.actionProps;
            if (!('buttonName' in actionNode.ActionValue) && !('position' in actionNode.ActionValue)) { 
                return result
            }
            this.props = actionNode.ActionValue as IButtonAddProps; 
            //ボタンを配置する
            const menuSpace = kintone.app.record.getHeaderMenuSpaceElement();
            if(!menuSpace) return result;
            if($("style#alc-button-add").length===0){
                const css=`
                `;
                const style = $("<style id='alc-button-add'>/<style>");
                style.text(css);
                $("head").append(style);
            }
            const button =$(`<button id='${this.props.eventName}' class='alc-button-normal' >${this.props.buttonName}</button>`);
            if(this.props.position==="一番左に追加する"){
                $(menuSpace).prepend(button);
            }else{
                $(menuSpace).append(button);
            }
            const clickEventName = `${event.type}.customButtonClick.${this.props.eventName}`;
            button.on("click",()=>{
                $(document).trigger(clickEventName,event);
            });
            return result;
        } catch (error) {
            event.error = error;
            console.error(error);
            result.canNext = false;
            return result;
        }
    }
  

    register(): void {
        actionAddins[this.name] = this;
    }

}
new ButtonAddAction();