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

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

interface ISpace{
    type:string,
    elementId: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,context:IContext): 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; 
            //ボタンを配置する
            let buttonSpace;
            if(this.props.space && this.props.space.elementId){
                buttonSpace = kintone.app.record.getSpaceElement(this.props.space.elementId);
            }else{
                buttonSpace = kintone.app.record.getHeaderMenuSpaceElement();
            }
            if(!buttonSpace) return result;
  
            const button =$(`<button id='${this.props.eventName}' class='alc-button-normal' >${this.props.buttonName}</button>`);
            if(this.props.position==="一番左に追加する"){
                $(buttonSpace).prepend(button);
            }else{
                $(buttonSpace).append(button);
            }
            const clickEventName = `${event.type}.customButtonClick.${this.props.eventName}`;
            button.on("click",()=>{
                $(document).trigger(clickEventName,event);
            });
            return result;
        } catch (error) {
            context.errors.handleError(error,actionNode);
            result.canNext = false;
            return result;
        }
    }
  

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

}
new ButtonAddAction();