import { createElement, createCheckbox, createRadiobox, Dropdown, validation, toDateValue, OptionBase } from "../ui";

export default class ScheduleItem extends OptionBase {
    _var = {};

    constructor(opt = {}) {
        super(opt);
    }

    get checkOccurOnce() { return this._var.container.querySelector('.schedule-id-box-occur-once>input'); }
    get checkOccurEvery() { return this._var.container.querySelector('.schedule-id-box-occur-every>input'); }
    get inputOccurOnce() { return this._var.container.querySelector('.schedule-id-occur-once'); }
    get inputOccurEvery() { return this._var.container.querySelector('.schedule-id-occur-every'); }
    get inputOccurStarting() { return this._var.container.querySelector('.schedule-id-occur-starting') }
    get inputOccurEnding() { return this._var.container.querySelector('.schedule-id-occur-ending') }

    changeDailyFrequency(once) {
        this.inputOccurOnce.disabled = !once;
        this.inputOccurEvery.disabled = once;
        this.inputOccurStarting.disabled = once;
        this.inputOccurEnding.disabled = once;
    }

    getParameters() {
        return {
            Enabled: this._var.container.querySelector('.schedule-id-enabled>input').checked,
            Schedule: {
                Frequency: Number(this.dropFrequency.selected.value),
                Daily: {
                    OcurrsOnce: this.checkOccurOnce.checked,
                    OcurrsOnceAt: this.inputOccurOnce.value,
                    OcurrsInterval: Number(this.inputOccurEvery.value),
                    StartingAt: this.inputOccurStarting.value,
                    EndingAt: this.inputOccurEnding.value
                },
                Monday: this._var.container.querySelector('.schedule-id-1>input').checked,
                Tuesday: this._var.container.querySelector('.schedule-id-2>input').checked,
                Wednesday: this._var.container.querySelector('.schedule-id-3>input').checked,
                Thursday: this._var.container.querySelector('.schedule-id-4>input').checked,
                Friday: this._var.container.querySelector('.schedule-id-5>input').checked,
                Saturday: this._var.container.querySelector('.schedule-id-6>input').checked,
                Sunday: this._var.container.querySelector('.schedule-id-7>input').checked,
                DayOfMonth: Number(this._var.container.querySelector('.schedule-id-dayofmonth').value),
                StartDate: this._var.container.querySelector('.schedule-id-duration-start').value,
                EndDate: this._var.container.querySelector('.schedule-id-duration-end').value
            }
        };
    }

    getDateTime(s) {
        if (typeof s === 'string') {
            const d = new Date(s);
            return isNaN(d.getTime()) ? new Date() : d;
        }
        return s;
    }

    getTimeString(s) {
        const d = this.getDateTime(s);
        return String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0');
    }

    getDateString(s) {
        const d = this.getDateTime(s);
        // return String(d.getMonth() + 1).padStart(2, '0') + '/' + String(d.getDate()).padStart(2, '0') + '/' + String(d.getFullYear());
        return toDateValue(d, true);
    }

    setParameters(p) {
        this._var.container.querySelector('.schedule-id-enabled>input').checked = p.Enabled;
        const schedule = p.Schedule || {};
        this.dropFrequency.select(String(schedule.Frequency));
        let checker = schedule.Daily.OcurrsOnce ? this.checkOccurOnce : this.checkOccurEvery;
        checker.checked = true;
        checker.dispatchEvent(new Event('change'));
        this.inputOccurOnce.value = this.getTimeString(schedule.Daily.OcurrsOnceAt);
        this.inputOccurEvery.value = String(schedule.Daily.OcurrsInterval);
        this.inputOccurStarting.value = this.getTimeString(schedule.Daily.StartingAt);
        this.inputOccurEnding.value = this.getTimeString(schedule.Daily.EndingAt);
        this._var.container.querySelector('.schedule-id-1>input').checked = schedule.Monday;
        this._var.container.querySelector('.schedule-id-2>input').checked = schedule.Tuesday;
        this._var.container.querySelector('.schedule-id-3>input').checked = schedule.Wednesday;
        this._var.container.querySelector('.schedule-id-4>input').checked = schedule.Thursday;
        this._var.container.querySelector('.schedule-id-5>input').checked = schedule.Friday;
        this._var.container.querySelector('.schedule-id-6>input').checked = schedule.Saturday;
        this._var.container.querySelector('.schedule-id-7>input').checked = schedule.Sunday;
        this._var.container.querySelector('.schedule-id-dayofmonth').value = String(schedule.DayOfMonth);
        this._var.container.querySelector('.schedule-id-duration-start').value = this.getDateString(schedule.StartDate);
        this._var.container.querySelector('.schedule-id-duration-end').value = this.getDateString(schedule.EndDate);
    }

    create() {
        const option = this._option;
        const drop = new Dropdown({ selected: '0' });
        this.dropFrequency = drop;
        drop.source = [
            { value: '0', text: 'Daily' },
            { value: '1', text: 'Weekly' },
            { value: '2', text: 'Monthly' }
        ];
        drop.onSelected = item => {
            container.querySelector('.schedule-item-weekly').style.display = item.value === '1' ? '' : 'none';
            const monthly = item.value === '2';
            container.querySelector('.schedule-item-monthly').style.display = monthly ? '' : 'none';
            if (!monthly) {
                const dayofmonth = this._var.container.querySelector('.schedule-id-dayofmonth');
                if (dayofmonth.classList.contains('validation-error')) {
                    dayofmonth.value = '1';
                }
            }
        };
        const container = createElement('div', 'schedule-item-container',
            createElement('fieldset', 'schedule-item-frequency',
                createElement('legend', legend => legend.innerText = 'Frequency'),
                createElement('div', 'schedule-item-line',
                    createElement('span', span => span.innerText = 'Occurs'),
                    drop.create()
                ),
                createElement('div', div => {
                    div.className = 'schedule-item-panel schedule-item-weekly';
                    div.style.display = 'none';
                },
                    createElement('table', 'schedule-item-table',
                        createElement('tr', 'schedule-item-tr',
                            createElement('td', null, createCheckbox({ className: 'schedule-id-1', label: 'Monday' })),
                            createElement('td', null, createCheckbox({ className: 'schedule-id-3', label: 'Wednesday' })),
                            createElement('td', null, createCheckbox({ className: 'schedule-id-5', label: 'Friday' })),
                            createElement('td', null, createCheckbox({ className: 'schedule-id-6', label: 'Saturday' }))
                        ),
                        createElement('tr', 'schedule-item-tr',
                            createElement('td', null, createCheckbox({ className: 'schedule-id-2', label: 'Tuesday' })),
                            createElement('td', null, createCheckbox({ className: 'schedule-id-4', label: 'Thursday' })),
                            createElement('td'),
                            createElement('td', null, createCheckbox({ className: 'schedule-id-7', label: 'Sunday' }))
                        )
                    )
                ),
                createElement('div', div => {
                    div.className = 'schedule-item-panel schedule-item-monthly';
                    div.style.display = 'none';
                },
                    createElement('div', 'schedule-item-line',
                        createElement('span', span => span.innerText = 'On day'),
                        validation(
                            createElement('input', i => { i.type = 'text', i.className = 'ui-input schedule-id-dayofmonth', i.maxLength = 2 }),
                            /^([0]?[1-9]|[12][0-9]|[3][01])$/
                        ),
                        createElement('span', span => span.innerText = 'of the month')
                    )
                )
            ),
            createElement('fieldset', 'schedule-item-daily-frequency',
                createElement('legend', legend => legend.innerText = 'Daily frequency'),
                createElement('div', 'schedule-item-line',
                    createRadiobox({
                        name: 'schedule-daily-occurs',
                        checked: true,
                        className: 'schedule-id-box-occur-once',
                        label: 'Occurs once at',
                        onchange: e => this.changeDailyFrequency(e.target.checked)
                    }),
                    validation(
                        createElement('input', i => { i.type = 'text', i.className = 'ui-input schedule-id-occur-once', i.maxLength = 5 }),
                        /^([1-9]|[01][0-9]|[2][0-3]):([1-9]|[0-5][0-9])$/
                    )
                ),
                createElement('div', 'schedule-item-line schedule-item-line-occur-every',
                    createRadiobox({
                        name: 'schedule-daily-occurs',
                        className: 'schedule-id-box-occur-every',
                        label: 'Occurs every',
                        onchange: e => this.changeDailyFrequency(!e.target.checked)
                    }),
                    validation(
                        createElement('input', i => { i.type = 'text', i.className = 'ui-input schedule-id-occur-every', i.maxLength = 5 }),
                        /^([0][1-9]+|[1-9][0-9]*)$/
                    ),
                    createElement('span', span => span.innerText = 'minute(s)'),
                    createElement('div', 'schedule-item-placeholder'),
                    createElement('div', 'schedule-item-block',
                        createElement('div', 'scheldule-item-line',
                            createElement('span', span => span.innerText = 'Starting at'),
                            validation(
                                createElement('input', i => { i.type = 'text', i.className = 'ui-input schedule-id-occur-starting', i.maxLength = 5 }),
                                /^([1-9]|[01][0-9]|[2][0-3]):([1-9]|[0-5][0-9])$/
                            )
                        ),
                        createElement('div', 'scheldule-item-line',
                            createElement('span', span => span.innerText = 'Ending at'),
                            validation(
                                createElement('input', i => { i.type = 'text', i.className = 'ui-input schedule-id-occur-ending', i.maxLength = 5 }),
                                /^([1-9]|[01][0-9]|[2][0-3]):([1-9]|[0-5][0-9])$/
                            )
                        )
                    )
                )
            ),
            createElement('fieldset', 'schedule-item-duration',
                createElement('legend', legend => legend.innerText = 'Duration'),
                createElement('div', 'schedule-item-line schedule-item-line-duration',
                    createElement('span', span => span.innerText = 'Start date'),
                    validation(
                        createElement('input', i => { i.type = 'date', i.className = 'ui-input schedule-id-duration-start', i.maxLength = 10, i.required = true, i.min = '1753-01-01', i.max = '9999-12-31' }),
                        /^[1-9][0-9]{3}-(1[0-2]|0[1-9])-(3[0-1]|[1-2][0-9]|0[1-9])$/
                    ),
                    createElement('div', 'schedule-item-placeholder'),
                    createElement('span', span => span.innerText = 'End date'),
                    validation(
                        createElement('input', i => { i.type = 'date', i.className = 'ui-input schedule-id-duration-end', i.maxLength = 10, i.required = true, i.min = '1753-01-01', i.max = '9999-12-31' }),
                        /^[1-9][0-9]{3}-(1[0-2]|0[1-9])-(3[0-1]|[1-2][0-9]|0[1-9])$/
                    )
                ),
                createElement('div', 'schedule-item-line',
                    createCheckbox({ className: 'schedule-id-enabled', checked: true, label: 'Enabled' })
                )
            )
        );
        this._var.container = container;
        if (option.parameter == null) {
            option.parameter = {
                Enabled: true,
                Schedule: {
                    Frequency: 0,
                    Daily: {
                        OcurrsOnce: true,
                        OcurrsOnceAt: '00:00',
                        OcurrsInterval: 60,
                        StartingAt: '00:00',
                        EndingAt: '23:00'
                    },
                    Monday: true,
                    Tuesday: false,
                    Wednesday: false,
                    Thursday: false,
                    Friday: false,
                    Saturday: false,
                    Sunday: false,
                    DayOfMonth: 1,
                    StartDate: '',
                    EndDate: ''
                }
            };
        }
        this.setParameters(option.parameter);
        return container;
    }
}