import { DatePickerOptions } from './datepicker_options';
import { BaseDatePickerComponent } from './base_datepicker';
import { Component, Provider, forwardRef, ViewEncapsulation, ChangeDetectionStrategy, Renderer, ElementRef, Input } from '@angular/core';
import { DaterangePickerConfig, DefaultDaterangePickerConfig, defaultDaterangePickerConfig } from "./daterangepicker_config";

const UI_DATERANGEPICKER_PROVIDER: Provider = {
    provide: BaseDatePickerComponent,
    useExisting: forwardRef(() => UIDaterangePickerComponent)
};

@Component({
    selector: 'ui-daterangepicker',
    template: `<input class="form-control dropdown-toggle" type="text" (click)="toggle()" (change)="change($event)" (blur)="blur($event)"/>
        <div ui-daterangepicker-inner [config]="config" (apply)="apply($event)" (cancel)="cancel($event)"></div>`,
    providers: [UI_DATERANGEPICKER_PROVIDER],
    encapsulation: ViewEncapsulation.None,
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class UIDaterangePickerComponent extends BaseDatePickerComponent {

    constructor(private _render: Renderer, private _eleRef: ElementRef) {
        super(_render, _eleRef);
    }

    public config: DaterangePickerConfig = defaultDaterangePickerConfig;

    initConfig(options: DatePickerOptions) {
        Object.assign(this.config, options);
    }

    apply($event: string) {
        super.writeValue($event);
        this.datepickerChange$.emit($event);
        this.change$.emit($event);
        this.hide();
    }

    cancel($event: boolean) {
        this.hide();
    }

    writeValue(value: string): void {
        if (!value) {
            super.writeValue(value);
            return;
        }

        let dates = value.split(this.config.separator);
        let nConfig: DaterangePickerConfig = new DefaultDaterangePickerConfig();
        if (dates.length >= 2) {
            Object.assign(nConfig, this.config, {
                'startDate': dates[0],
                'endDate': dates[1]
            });
        } else 

        this.config = nConfig;

        super.writeValue(value);
    }
}
{
            Object.assign(nConfig, this.config, {
                'startDate': value,
                'endDate': undefined
            });
        }