<template>
    <table>
        <tbody>
            <RowForm label='Name'>
                <input-form name='name' id='name' :value='name' @update:value='name = $event'></input-form>
            </RowForm>
            <RowForm label='Description'>
                <input-form name='description' id='description' @update:value="description = $event" attibute="description" :value='description'></input-form>
            </RowForm>
            <input-date placeholder="dd/mm/yyyy" label="Start Date" :value="date" @update:date="date = $event"></input-date>
            <input-time label="Start time" :value="time" @update:time="time = $event"></input-time>
            <every label="   minute(s)" :value="every" @update:value="every = $event"></every>
        </tbody>
    </table>
    <div class="row">
        <div class="col d-flex justify-content-end" style="margin-top: 20px;margin-bottom: 20px;">
            <button class="btn btn-primary btn-sm" id="btn_save" type="button" style="width: 80px;margin-right: 10px;margin-left: 10px;background: #769b76;border-color: #dddddd;" @click='save'>Save</button>
            <button class="btn btn-primary btn-sm" id="btn_save" type="button" style="width: 80px;margin-right: 10px;margin-left: 10px;background: #946464;border-color: #dddddd;" @click='cancel'>Cancel</button>
        </div>
    </div>
</template>
<script lang="ts">
import RowForm from '@/lib-components/component/RowForm.vue';
import InputForm from '@/lib-components/component/InputForm.vue';
import InputDate from '@/lib-components/component/InputDate.vue';
import InputTime from '@/lib-components/component/InputTime.vue';
import Every from '@/lib-components/component/Schedule/Every.vue';
import { Attribute } from '@/domain/models/Attribute.interface';
import { TaskService } from '@/domain/services/Task.service';
import { ScheduleType } from '@/domain/models/tasks/enums/ScheduleType.enum';
import { Response } from '@/domain/models/Response.interface';
import { jsonUtilities } from '@/infrastructure/utilities/jsonUtilities';

export default{
    name: 'ContinuousSchedule',
    components:{
        RowForm,
        InputForm,
        InputDate,
        InputTime,
        Every
    },
    data:()=>{
        return {
            date: new Date(),
            time: new Date(),
            attributes: [],
            taskService: {} as TaskService,
            response: {} as Response,
            name: '',
            description: '',
            every: '',
            isEdit: false,
        }
    },
    props: {
        taskId: { type: String, default: '' },
        scheduleData: {} as any,
        scheduleId : { type: String, default: '' },
    },
    mounted(){
        this.taskService = new TaskService();
        if(this.scheduleData.attributes != undefined)
        {
            this.name = jsonUtilities.getJsonArrayEntrybyValue<Attribute>(this.scheduleData.attributes, 'task_name').value;
            this.description = jsonUtilities.getJsonArrayEntrybyValue<Attribute>(this.scheduleData.attributes, 'task_description').value;
            this.every = jsonUtilities.getJsonArrayEntrybyValue<Attribute>(this.scheduleData.attributes, 'schedule_recurrence').value;
            let attributeDate = jsonUtilities.getJsonArrayEntrybyValue<Attribute>(this.scheduleData.attributes, 'schedule_begin_date').value;
            let attributeTime = jsonUtilities.getJsonArrayEntrybyValue<Attribute>(this.scheduleData.attributes, 'schedule_begin_time').value;
            this.date = new Date(Date.parse(attributeDate.substring(0,4) + "/" + attributeDate.substring(4,6) + "/" + attributeDate.substring(6) + " " + (attributeTime.substring(0,2) + ":" + attributeTime.substring(2))));
            this.time = this.date;
            this.isEdit = true;
        }
    },
    methods: {
        cancel(){
            this.$emit('cancel');
        },
        async save(){
            let schedule : {[k: string]: any} = {};
            this.attributes = [];
            this.addAttribute('task_name', this.name);
            this.addAttribute('task_description', this.description);
            this.addAttribute('schedule_type', ScheduleType.Continuous);
            this.addAttribute('schedule_begin_date', this.date.toISOString().slice(0,10).replace(/-/g,""));
            this.addAttribute('schedule_begin_time', this.time.toTimeString().split(' ')[0].slice(0, -3).replace(":",""));
            this.addAttribute('schedule_recurrence', this.every);
            this.addAttribute('schedule_task_id', this.taskId);
            schedule.attributes = this.attributes;
            if(this.isEdit){
                await this.taskService.updateSchedule(this.scheduleId, ScheduleType.Continuous, JSON.stringify(schedule))
                .then((response: Response) => {
                    this.$emit('save', response.responseText, response.status);
                })
                .catch((error :string) => {
                    this.$emit('save', error);
                });
            }else{
                await this.taskService.addSchedule(ScheduleType.Continuous, JSON.stringify(schedule))
                .then((response: Response) => {
                    this.$emit('save', response.responseText, response.status);
                })
                .catch((error :string) => {
                    this.$emit('save', error);
                });
            }
        },
        addAttribute(attributeName : string, value : string){
            let attribute = {}  as Attribute;
            attribute.attribute = attributeName;
            attribute.value = value;
            this.attributes.push(attribute);
        },
    },
}
</script>