import * as React from "react";
import { RecordService, CachingService } from "../Services";
import { CustomEntityFilter, RecordField, FieldQuery } from "../Models";
import { FieldTypes } from "../Enums";
import { Dropdown } from "../Customizations/Controls/Dropdown";
import { Label, DatePicker, IDatePickerStrings } from "office-ui-fabric-react";

import './FiltersControl.css'
import { DateUtils } from "../Utils";

export class FiltersControl extends React.Component<any, any> {
    private _recordService: RecordService = new RecordService();
    private _cachingService: CachingService = new CachingService();
    private datepickerStrings: IDatePickerStrings;
    private _dateUtils: DateUtils = new DateUtils();

    private selectedFilters:any[]=[];
    constructor(props: any) {
        super(props);
        
        this.state = {
            fields: []
        }

        this.getEmptyRecord();

        if (this._cachingService.readPersistant("Language") != 1) {
            this.datepickerStrings = {
                days: [
                    "Sunday",
                    "Monday",
                    "Tuesday",
                    "Wednsday",
                    "Thursday",
                    "Friday",
                    "Saturday"
                ],
                goToToday: "Go to today",
                months: [
                    "January",
                    "February",
                    "March",
                    "April",
                    "May",
                    "June",
                    "July",
                    "August",
                    "September",
                    "October",
                    "November",
                    "December"
                ],
                shortDays: ["S", "M", "T", "W", "T", "F", "S"],
                shortMonths: [
                    "Jan",
                    "Feb",
                    "Mar",
                    "Apr",
                    "May",
                    "June",
                    "July",
                    "Aug",
                    "Sept",
                    "Oct",
                    "Nov",
                    "Dec"
                ]
            };
        } else {
            this.datepickerStrings = {
                days: [
                    "الاحد",
                    "الاثنين",
                    "الثلاثاء",
                    "الاربعاء",
                    "الخميس",
                    "الجمعة",
                    "السبت"
                ],
                goToToday: "اذهب الي اليوم",
                months: [
                    "يناير",
                    "فبراير",
                    "مارس",
                    "ابريل",
                    "مايو",
                    "يونيو",
                    "يوليو",
                    "اغسطس",
                    "سبتمبر",
                    "اكتوبر",
                    "نوفمبر",
                    "ديسمبر"
                ],
                shortDays: ["ح", "ن", "ث", "ع", "خ", "ج", "س"],
                shortMonths: [
                    "يناير",
                    "فبراير",
                    "مارس",
                    "ابريل",
                    "مايو",
                    "يونيو",
                    "يوليو",
                    "اغسطس",
                    "سبتمبر",
                    "اكتوبر",
                    "نوفمبر",
                    "ديسمبر"
                ]
            };
        }
    }

    private getEmptyRecord() {
        this._recordService.getEmptyRecord(this.props.entityId).then(
            result => {
                this.setState({ fields: result.fields });
            },
            error => {
                alert(error);
            }
        );
    }

    private getField(fieldId: number): RecordField {
        let output = new RecordField();
        this.state.fields.forEach((field: RecordField) => {
            if (field.id == fieldId)
                output = field;
        });
        return output;
    }

    private _onFormatDate = (date: any): string => {
        // return date.getDate() + '/' + (date.getMonth() + 1) + '/' + (date.getFullYear() % 100);
        return this._dateUtils.formatDateTime(date);
    };

    private applyQuery(query:FieldQuery, value:any, between_second: boolean = false){
        let valueAlreadyExists=false;
        let anyChangeDone;

        this.selectedFilters.forEach((filter:any)=>{
            if(filter.query==query){
                if(query.queryOperator==5){
                    if(between_second==true && filter.value1!=value){
                        anyChangeDone=true;
                        filter.value1=value    
                    }
                    else if(between_second!=true && filter.value!=value){
                        anyChangeDone=true;
                        filter.value=value    
                    }
                }
                else {
                    if(filter.value!=value){
                        anyChangeDone=true;
                        filter.value=value
                    }
                }
                valueAlreadyExists=true
            }
        })

        if(valueAlreadyExists == false){
            anyChangeDone=true;
            if(query.queryOperator==5){
                
                var filter:any={'query':query}
                
                if(between_second==true)
                    filter.value1=value    
                else
                    filter.value=value    

                this.selectedFilters.push(filter)
            }
            else
                this.selectedFilters.push({'query':query,'value':value})
        }

        if(anyChangeDone==true){
            let fieldQueries:FieldQuery[]=[];

            this.selectedFilters.forEach((filter:any)=>{

                if(filter.query.queryOperator==5){
                    if(filter.value || filter.value1){

                        if(!filter.value)
                            filter.query.value=this._dateUtils.formatToServerDateTime(new Date(1900, 1, 1, 0, 0, 0, 0));
                        else 
                            filter.query.value=this._dateUtils.formatToServerDateTime(filter.value);

                        if(!filter.value1)
                            filter.query.value1=this._dateUtils.formatToServerDateTime(new Date(2100, 1, 1, 0, 0, 0, 0));
                        else
                            filter.query.value1=this._dateUtils.formatToServerDateTime(filter.value1);
                        
                        fieldQueries.push(filter.query)
                    }
                }
                else if(filter.value!='all' && filter.value){
                    if(filter.query.value!=filter.value){
                        filter.query.value=filter.value
                        fieldQueries.push(filter.query)
                    }
                }
            })

            this.props.applyFilters(fieldQueries);
        }
    }

    private changeSingleChoiceFilter(field: RecordField, query: any, value: any) {
        this.applyQuery(query,value.key)
    }

    private changeDateFilter(field: RecordField, query: any,between_second: boolean, value: any) {
        this.applyQuery(query,value,between_second)
    }

    private getInputElement(field: RecordField, query: FieldQuery, between_second: boolean = false): any {
        if (field.type == FieldTypes.SingleChoice) {
            return <Dropdown
                onChanged={this.changeSingleChoiceFilter.bind(this, field, query)}
                field={field}
                className=" ms-lg12"
                defaultSelectedKey='all'
                options={[{ key: 'all', text: 'All' }].concat(field.lookups.map((lookup: any) => {
                    return { key: lookup.id, text: lookup.value };
                }))}
            />;
        }
        else
            if (field.type == FieldTypes.Date) {

                let value:any=null;
                this.selectedFilters.forEach((filter:any)=>{
                    if(filter.query==query){
                        value=between_second==true?filter.value1:filter.value
                    }
                });

                console.log(value)
                
                return <DatePicker
                    className=" ms-lg12"
                    placeholder=""
                    value={value}
                    strings={this.datepickerStrings}
                    allowTextInput={true}
                    //isRequired={!item.allowNull}
                     onSelectDate={this.changeDateFilter.bind(
                         this,
                         field, query,between_second
                     )}
                    formatDate={this._onFormatDate.bind(this)}
                />;
            }
        return "";
    }

    private getQueryOperator(query: FieldQuery, between_second: boolean = false) {
        if (query.queryOperator == 0) {
            return "="
        }
        else if (query.queryOperator == 1) {
            return "!="
        }
        else if (query.queryOperator == 2) {
            return "<"
        }
        else if (query.queryOperator == 3) {
            return ">"
        }
        else if (query.queryOperator == 4) {
            return "contains"
        }
        else if (query.queryOperator == 5) {
            return between_second == true ? "<=" : ">="
        }

        return "";
    }

    public render(): JSX.Element {

        return (<div className='FiltersContainer'>

            <div className="LinkingDiv"></div>
            <div className="ms-Grid">
                {this.props.filters.map((filter: CustomEntityFilter) => {
                    if (filter.criteria.query.length > 0) {

                        let query = filter.criteria.query[0];
                        let field = this.getField(query.fieldId)

                        return query.queryOperator == 5 ?
                            (<div className={'ms-Grid-col ms-lg6'}>
                                <div><Label style={{ textAlign: 'right' }} className={'ms-Grid-col ms-lg4'} >{field.displayName} {this.getQueryOperator(filter.criteria.query[0])}</Label>
                                    <div className={'ms-Grid-col ms-lg8'}>{this.getInputElement(field, query)}</div>
                                </div>
                                <div style={{ clear: 'both' }}><Label style={{ textAlign: 'right' }} className={'ms-Grid-col ms-lg4'} >{this.getQueryOperator(filter.criteria.query[0], true)}</Label>
                                    <div className={'ms-Grid-col ms-lg8'}>{this.getInputElement(field, query, true)}</div>
                                </div>
                            </div>) :

                            (<div className={'ms-Grid-col ms-lg6'}>
                                <Label style={{ textAlign: 'right' }} className={'ms-Grid-col ms-lg4'} >{field.displayName} {this.getQueryOperator(filter.criteria.query[0])}</Label>
                                <div className={'ms-Grid-col ms-lg8'}>{this.getInputElement(field, query)}</div>
                            </div>)

                    }
                    return "";
                })}
            </div>
        </div>);
    }
}