import ngModule from '../../module';
import Field from '../field';

class DatePicker extends Field {
    constructor($element, $scope, $compile) {
        super($element, $scope, $compile);

        this.input = $compile(`<input type="date"></input>`)($scope)[0];
        this.input.addEventListener('change', () => this.onValueUpdate());
    }

    onValueUpdate() {
        let date = null;
        let value = this.input.value;

        if (value) {
            let ymd = value.split('-')
                .map(e => parseInt(e));
            date = new Date(ymd[0], ymd[1] - 1, ymd[2]);

            if (this.field) {
                let orgDate = this.field instanceof Date
                    ? this.field
                    : new Date(this.field);

                date.setHours(
                    orgDate.getHours(),
                    orgDate.getMinutes(),
                    orgDate.getSeconds(),
                    orgDate.getMilliseconds()
                );
            }
        }

        super.field = date;
        this.$.$applyAsync();
    }

    get field() {
        return super.field;
    }

    set field(value) {
        super.field = value;
        this.input.value = this.$filter('date')(value, 'yyyy-MM-dd');
    }
}
DatePicker.$inject = ['$element', '$scope', '$compile'];

ngModule.vnComponent('vnDatePicker', {
    controller: DatePicker,
    bindings: {
        options: '<?'
    }
});