import * as React from "react";
import { TextField } from "office-ui-fabric-react/lib/components/TextField";
import { Label } from 'office-ui-fabric-react/lib/components/Label';
import { Dropdown } from 'office-ui-fabric-react/lib/components/Dropdown';
import { Checkbox } from 'office-ui-fabric-react/lib/components/Checkbox';
import { Image } from 'office-ui-fabric-react/lib/Image';
import { RecordField, WorkflowAction } from "../Models";
import {  FileService } from "../Services";
import { FieldTypes } from "../Enums";
import { DatePicker } from "office-ui-fabric-react/lib/components/DatePicker/DatePicker";
import { ChoiceGroup } from "office-ui-fabric-react/lib/components/ChoiceGroup/ChoiceGroup";
import './FormDisplay.css'
import { Link, Callout, IconButton, createRef,ComboBox, PrimaryButton } from "office-ui-fabric-react";
import { RecordsListView } from "./RecordsListView";
export class ViewForm extends React.Component<any, any> {
    [x: string]: any;
    private _fileService : FileService = new FileService();
    private _menuButtonElement = createRef<HTMLElement>();
    constructor(props: any) {
        super(props);
        this.state = {
            isCalloutVisible: false
        };
    }

    public render() {
        return (
            <div>
                {
                    this.props.Record.state?
                    <h4>{this.props.Record.state.name}</h4>:""
                }
                {
                    this.props.Record && this.props.Record.actions && this.props.Record.actions.length>0?
                    <div>
                    {
                    this.props.Record.actions.map((action: WorkflowAction) => {
                            return <div style={{display:"inline-block"}}>
                            
                                <PrimaryButton
                                    onClick={this.props.OnExecuteWorkflowAction(this.props.Record, action)}
                                    className="panel-footer-btn">
                                    {action.name}
                                </PrimaryButton>
                            </div>
                        }) 
                    }</div>: ""
                }
            <div className="">
               
                <div className="formPreview">
                    
                    {
                        !this.props.Record.fields ? "":
                        this.props.Record.fields.sort((a: RecordField, b: RecordField) => {
                            if (a.index < b.index) {
                                return -1;
                            }
                            if (a.index > b.index) {
                                return 1;
                            }
                            return 0;
                        }).map((item: RecordField) => {
                            switch (item.type) {
                                case FieldTypes.Text:
                                    return <div className="ms-Grid-col ms-sm6 ms-md6 ms-lg12" key={`form-field-${item.index}`}>
                                        <TextField className="ms-Grid-col ms-lg12" label={item.displayName} value={item.data} onChanged={this._handleDataChange.bind(this,item) }disabled={true}/>
                                        
                                    </div>;
                                case FieldTypes.Header:
                                    return <div className="ms-Grid-col ms-sm6 ms-md6 ms-lg12" key={`form-field-${item.index}`}>
                                        <h3 className="ms-Grid-col ms-lg12">{item.displayName}</h3>
                                        
                                    </div>
                                case FieldTypes.Paragraph:
                                    return <div className="ms-Grid-col ms-sm6 ms-md6 ms-lg12" key={`form-field-${item.index}`}>
                                        <p className="ms-Grid-col ms-lg12">{item.displayName}</p>
                                        
                                    </div>
                                case FieldTypes.SingleChoice:
                                    return <div className="ms-Grid-col ms-sm6 ms-md6 ms-lg12" key={`form-field-${item.index}`}>
                                        <Dropdown className="ms-Grid-col ms-lg12" 
                                        defaultSelectedKey={item.data}
                                        options={item.lookups.map((lookup:any)=>{
                                                    return {key:lookup.id,text:lookup.value}
                                                })} 
                                        label={item.displayName} 
                                        onChanged={this._handleChoiceChange.bind(this,item)} disabled={true}/>
                                        
                                    </div>;
                                case FieldTypes.MultipleChoice:
                                    return <div className="ms-Grid-col ms-sm6 ms-md6 ms-lg12" key={`form-field-${item.index}`}>
                                    {
                                        item.lookups.map((lookup:any)=>{
                                                return <Checkbox className="ms-Grid-col ms-lg12" disabled={true} defaultChecked={this.isChecked(item,lookup.id)} key={lookup.id} label={lookup.value}  onChange={this._handleCheckboxChange.bind(this,item,lookup.id)}/>                                                
                                            })
                                    }  
                                    </div>
                                case FieldTypes.Multiline:
                                    return <div className="ms-Grid-col ms-sm6 ms-md6 ms-lg7" key={`form-field-${item.index}`}>
                                        <TextField disabled={true} className="ms-Grid-col ms-lg11" label={item.displayName} multiline rows={4}  value={item.data} onChanged={this._handleDataChange.bind(this,item)}/>
                                        
                                    </div>
                                case FieldTypes.Image:
                                    return <div className="ms-Grid-col ms-sm6 ms-md6 ms-lg7" key={`form-field-${item.index}`}>
                                        <div className="ms-Grid-col ms-lg12"> <Label>{item.displayName}</Label>
                                            <Image
                                                src={this.getFileFullPath(item.extraData)}
                                                alt={item.displayName}
                                                width={100}
                                                onClick={this.downloadFile(item)}
                                            />
                                        </div>  
                                        <input type="file" id={'uploadFile' + item.id} onChange={(event)=> {this.uploadFile(event,item)}} ></input>                                      
                                    </div>

                                case FieldTypes.Label:
                                    return <div className="ms-Grid-col ms-sm6 ms-md6 ms-lg12" key={`form-field-${item.index}`}>
                                        <Label className="ms-Grid-col ms-lg11">{item.displayName}</Label>
                                    </div>
                                case FieldTypes.Date:
                                    return <div className="ms-Grid-col ms-sm6 ms-md6 ms-lg12" key={`form-field-${item.index}`}>
                                       <Label>{item.displayName}</Label>
                                        <DatePicker
                                        className="ms-Grid-col ms-lg12"
                                        value={this.convertDate(item.data)}
                                            isRequired={false}
                                            placeholder="Select a date..."
                                            allowTextInput={true}
                                            onSelectDate={this._handleDataChange.bind(this,item)} disabled={true}
                                        />
                                        
                                    </div>
                                case FieldTypes.Currency:
                                    return <div className="ms-Grid-col ms-sm6 ms-md6 ms-lg12" key={`form-field-${item.index}`}>
                                        <TextField iconProps={{ iconName: 'Money' }} className="ms-Grid-col ms-lg12"
                                         label={item.displayName} value={item.data}
                                         onChanged={this._handleDataChange.bind(this,item)} disabled={true}/>
                                        

                                    </div>;
                                case FieldTypes.Percentage:
                                    return <div className="ms-Grid-col ms-sm6 ms-md6 ms-lg12" key={`form-field-${item.index}`}>
                                        <TextField iconProps={{ iconName: 'Chart' }} className="ms-Grid-col ms-lg12"
                                         label={item.displayName} value={item.data}
                                         onChanged={this._handleDataChange.bind(this,item)} disabled={true}/>
                                    
                                    </div>;
                                case FieldTypes.Number:
                                    return <div className="ms-Grid-col ms-sm6 ms-md6 ms-lg12" key={`form-field-${item.index}`}>
                                        <TextField iconProps={{ iconName: 'NumberField' }} className="ms-Grid-col ms-lg12" 
                                        label={item.displayName} value={item.data}
                                        onChanged={this._handleDataChange.bind(this,item)} disabled={true}/>
                                       

                                    </div>;
                                case FieldTypes.Boolean:
                                    return <div className="ms-Grid-col ms-sm6 ms-md6 ms-lg7" key={`form-field-${item.index}`}>
                                        <div className="choiceGroup ms-Grid-col ms-lg11">
                                            <ChoiceGroup
                                                options={[
                                                    {
                                                        key: 'true',
                                                        text: 'Yes',
                                                        disabled: false

                                                    },
                                                    {
                                                        key: 'false',
                                                        text: 'No',
                                                        disabled: false

                                                    },

                                                ]}
                                                onChange={this._handleBooleanChange.bind(this,item)}
                                                label={item.displayName}
                                                defaultSelectedKey={item.data?item.data.toString():'false'} disabled={true}
                                            />
                                        </div>                                        
                                    </div>;
                                    case FieldTypes.Document:
                                        return <div className="ms-Grid-col ms-sm6 ms-md6 ms-lg7" key={`form-field-${item.index}`}>
                                            <Label>{item.displayName}</Label>
                                            <Link disabled={true} className="choiceGroup ms-Grid-col ms-lg11" value={item.data} onClick={this.downloadFile(item)}>{item.extraData?item.extraData.name:""}</Link>
                <input type="file" id={'uploadFile' + item.id} onChange={(event)=> {this.uploadFile(event,item)}} ></input>

                                    </div>;
                                    case FieldTypes.Callout:
                                        return <div className="ms-Grid-col ms-sm6 ms-md6 ms-lg5" key={`form-field-${item.index}`}>
                                            <div className="choiceGroup ms-Grid-col ms-lg10">
                                                <div className="buttonArea" ref={this._menuButtonElement}>
                                                    <IconButton
                                                        iconProps={{ iconName: 'Chat' }}
                                                        onClick={this._onShowMenuClicked}

                                                    />
                                                </div>
                                                <Callout 
                                                    className="ms-CalloutExample-callout callout"
                                                    ariaLabelledBy={'callout-label-1'}
                                                    ariaDescribedBy={'callout-description-1'}
                                                    role={'alertdialog'}
                                                    gapSpace={0}
                                                    target={this._menuButtonElement.value}
                                                    onDismiss={this._onCalloutDismiss}
                                                    setInitialFocus={true}
                                                    hidden={!this.state.isCalloutVisible} 
                                                >

                                                    <div className="ms-CalloutExample-inner calloutContent">
                                                        <div className="ms-CalloutExample-content">
                                                            <p className="ms-CalloutExample-subText" id={'callout-description-1'}>
                                                                {item.displayName}
                                                            </p>
                                                        </div>

                                                    </div>
                                                </Callout>
                                            </div>
                                    </div>;
                                    case FieldTypes.EntityReference:
                                    return item.records?<div className="ms-Grid-col ms-sm6 ms-md6 ms-lg7" key={`form-field-${item.index}`}>
                                        <div className="choiceGroup ms-Grid-col ms-lg11">
                                            <ComboBox disabled={true}
                                            defaultSelectedKey={item.data}
                                                selectedKey="C"
                                                label={item.displayName}
                                                id="Basicdrop3"
                                                ariaLabel="Basic ComboBox example"
                                                allowFreeform={false}
                                                autoComplete="on"
                                                options={item.records.records.map((record: any) => { return { key: record.id, text: record.name } })}
                                                onRenderOption={this._onRenderFontOption}
                                                // tslint:disable:jsx-no-lambda
                                                onFocus={() => console.log('onFocus called')}
                                                onBlur={() => console.log('onBlur called')}
                                                onMenuOpen={() => console.log('ComboBox menu opened')}
                                                onChanged={this._handleDataChange.bind(this,item)}
                                            // tslint:enable:jsx-no-lambda
                                            />
                                        </div>
                                    </div>:""
                                    case FieldTypes.ReferencedEntity:
                                    case FieldTypes.ManyToManyRelated:
                                    return item.records? <div className="ms-Grid-col ms-sm6 ms-md6 ms-lg7" key={`form-field-${item.type}${item.index}`}>
                                        <div className="choiceGroup ms-Grid-col ms-lg11">
                                        <RecordsListView Records={item.records.records}></RecordsListView>
                                        </div>
                                    </div>:""

                            }
                            return ""
                        })
                    }
                </div>
            </div>
            </div>
        )
    }
    private _onShowMenuClicked = (): void => {
        this.setState({
            isCalloutVisible: !this.state.isCalloutVisible
        });
    };

    private _onCalloutDismiss = (): void => {
        this.setState({
            isCalloutVisible: false
        });
    };
    _handleDataChange(item:RecordField,value: any) {
        item.data = value;
    };
    _handleBooleanChange(item:RecordField,ev: React.FormEvent<HTMLElement>, selected:any){
        //debugger;
        item.data = selected.key;
    }
//     _handleDatePickerChange(item:RecordField,value: Date) {
//         debugger;
//         let date = new Date(value.toLocaleDateString());
// item.data = new Date(date.getFullYear(),date.getMonth(),date.getDate());
//     };
    _handleChoiceChange(item:RecordField,value: any) {
        item.data = value.key;
    };
    _handleCheckboxChange(item:RecordField,lookupId:number,ev: React.FormEvent<HTMLElement>, isChecked: boolean){
        if(!item.data){
            item.data = [];
        }

        if(isChecked && !item.data.includes(lookupId)){
            item.data.push(lookupId);
        }
        else if (!isChecked){
            item.data.splice(item.data.indexOf(lookupId), 1 );
        }
    }
    private isChecked(item:RecordField,lookupId:number){
        if(!item.data)
            return false;
        return item.data.includes(lookupId);
    }
    private convertDate(date:any) :Date|undefined{
        if(date==null)
            return undefined;

        if(date instanceof Date)
            return date;

        return new Date(date.replace('T', ' '));
        // // replace anything but numbers by spaces
        // dtstr = dtstr.replace(/\D/g," ");
      
        // // trim any hanging white space
        // dtstr = dtstr.replace(/\s+$/,"");
      
        // // split on space
        // let dtcomps : Array<string>= dtstr.split(" ");
      
        // // not all ISO 8601 dates can convert, as is
        // // unless month and date specified, invalid
        // if (dtcomps.length < 3) return "";
        // // if time not provided, set to zero
        // if (dtcomps.length < 4) {
        //   dtcomps[3] = "0";
        //   dtcomps[4] =  "0";
        //   dtcomps[5] =  "0";
        // }
      
        // // modify month between 1 based ISO 8601 and zero based Date
        // dtcomps[1] = (parseInt(dtcomps[1]) - 1).toString();
      
        // var convdt = new
        //     Date(Date.UTC(parseInt(dtcomps[0]),parseInt(dtcomps[1]),parseInt(dtcomps[2]),parseInt(dtcomps[3]),parseInt(dtcomps[4]),parseInt(dtcomps[5])));
      
        // return convdt.toUTCString();
    }

    private getFileFullPath(file: any) {
        return this._fileService.getFullPath(file);
    }
    private uploadFile(event: any,field:RecordField){
        if (event.target.files && event.target.files.length > 0) {
            const formData = new FormData();

            for (let file of event.target.files)
                formData.append(file.name, file)

            this._fileService.uploadFileContent(formData).then((result)=>{
                field.extraData = result;
                field.data = field.extraData.id;
            });            
        }
    }
    
    private downloadFile(field:RecordField){
        return (): void => {
            if(field.extraData){
                window.open(this._fileService.getFullPath(field.extraData));
            }
        }
    }
}
