import React from "react"
import {useState,useEffect, useRef} from 'react';
import { useForm, SubmitHandler } from "react-hook-form"
import Form from 'react-bootstrap/Form';
import FloatingLabel from 'react-bootstrap/FloatingLabel';
import InputGroup from 'react-bootstrap/InputGroup';

import 'bootstrap/dist/css/bootstrap.min.css';


import './controls.css'



function EntityControl(props)
{    
   


    const [Entity, setEntity] = useState(undefined);

    // const [Course, setCourse] = useState('');
    const [PositionDragged, setPositionDragged] = useState(false);
    // const [Speed, setSpeed] = useState();
    
    const [formData, setFormData] = useState({name: "",course: "" ,speed: 0,position: [0,0],height:0});
   
    
      
    useEffect(() => {    // Update the document title using the browser API    document.title = `You clicked ${count} times`;  

        // console.log(props.Entity);

            if(props.Entity !== undefined)
            {
                console.log(props.Entity)
                if(Entity === undefined)
                {
                    setEntity(props.Entity);
                    setFormData({name:props.Entity.Name,course:props.Entity.Course,speed:props.Entity.Speed,position:props.Entity.Position,height:props.Entity.Height })

                }else if(Entity.id !== props.Entity.id)
                {
                    setEntity(props.Entity);
                    setFormData({name:props.Entity.Name,course:props.Entity.Course,speed:props.Entity.Speed,position:props.Entity.Position,height:props.Entity.Height})

                } else if(Entity.id === props.Entity.id && Entity.Position !== props.Entity.Position)
                {
                    setFormData({...formData,position:props.Entity.Position,height:props.Entity.Height})
                    setPositionDragged(true);
                    

                }
                // setFormData({name:props.Entity.Name,course:props.Entity.Course,speed:props.Entity.Speed,position:props.Entity.Position})

            }

      

      
        
    },[props.Entity,props]);

    useEffect(() => {
        if(props.PositionCliecked !== undefined)
        {
            console.log(props.PositionCliecked)
            var pos = [0,0];
            pos[0] = props.PositionCliecked.lat;
            pos[1] = props.PositionCliecked.lng
            setFormData({...formData,position:pos});
        }

    },[props.PositionCliecked])




    // Entity.Entity.Course
const handleClick = (e) => {
        if(e.detail === 2)
        {   
            console.log(e)
            // setCourseInControl(true);
            e.target.readOnly = false;
            // e.target.style = "border: 1px solid"
        }
    };  

    const handleCourseInput= (e) => {
        // console.log(e.currentTarget.value)
        // console.log(isNaN(e.nativeEvent?.data))
        // if(!isNaN(e.nativeEvent?.data))
        if(Number.isInteger(parseFloat(e.currentTarget.value))  |  e.nativeEvent?.data === null )
        {
            setFormData({...formData,course:e.currentTarget.value});
            if(props.Entity !== undefined) 
            {
                props.Entity.Course = e.currentTarget.value.replace(",",".");

            }
        }

        
        
        // if(e.currentTarget.value === "")
        //     {
        //         setFormData({...formData,course:0});
        //         props.Entity.Course = 0;


        //     }   
        };

        const handleSpeedInput= (e) => {
            // console.log(e.nativeEvent?.data)
            // if(!isNaN(e.nativeEvent?.data))
            if(Number.isInteger(parseFloat(e.currentTarget.value)) |  e.nativeEvent?.data === null )
            {
               
                setFormData({...formData,speed:e.currentTarget.value});
                if(props.Entity !== undefined) 
                {
                    props.Entity.Speed = e.currentTarget.value.replace(",",".");
                }

            } 
            // if(e.nativeEvent?.data == null)
            // {
            //     setFormData({...formData,speed:0});
            //     props.Entity.Speed = 0;


            // }   

            // console.log(formData.speed)
        };

        const handleNameInput = (e) => {
            setFormData({...formData,name:e.currentTarget.value});

        }

        
        const handleInput = (e) => {
            // console.log(e.target.name)
            switch (e.target.name) {
                case "Lat":
                
                    if(Number.isInteger(parseFloat(e.currentTarget.value)) | e.nativeEvent?.data === null)
                    {
                        // e.currentTarget.value = e.currentTarget.value.replace(",",".");
                        setFormData({...formData,position:[e.currentTarget.value,formData.position[1],formData.position[2]] });
                    }
                    if(props.Entity !== undefined)
                    {
                        props.Entity.Position[0]=e.currentTarget.value.replace(",",".");    
                    }
                    break;
            case "Lon":
                if(Number.isInteger(parseFloat(e.currentTarget.value)) | e.nativeEvent?.data === null)
                {

                    setFormData({...formData,position:[formData.position[0],e.currentTarget.value,formData.position[2]] });
                    if(props.Entity !== undefined)
                    {
                        props.Entity.Position[1]=e.currentTarget.value.replace(",",".");   
                    }

                }
                // else if(e.nativeEvent?.data == null) {
                //     // setFormData({...formData,position:[formData.position[0],0,formData.position[2]] });

                // }


                break;
            case "Height":
                setFormData({...formData,height:e.currentTarget.value.replace(",",".")});
                if(props.Entity !== undefined)
                    {
                        props.Entity.Height=e.currentTarget.value.replace(",",".");   
                    }

                break;
                default:
                    break;
            }
            setPositionDragged(true);
        }

        const emptyForm= (e) =>
        {
            if(props.Entity !== undefined)
            {
                props.Entity.onFocus = undefined;
            }            
            setFormData({name:'',course:'',speed:'',position:['','']})
            setEntity(undefined)
            props.Functions.resetEntityOnFocus();

        }

        const resetForm = (e)=>
        {
            if(props.Entity !== undefined)
            {
                console.log("resetting")
                setFormData({name:props.Entity.Name,course:Entity.Course,speed:Entity.Speed,position:Entity.Position})
                props.Entity.Position = Entity.Position;
                props.Entity.Course = Entity.Course;
                props.Entity.Speed = Entity.Speed;
            }
            else {
                emptyForm();
            }
        }

        // const handleChange = (event) => {
        //     const { name, value } = event.target;
        //     setFormData((prevFormData) => ({ ...prevFormData, [name]: value }));
        //   };

        const handleSubmit = (e) => {
            e.preventDefault();
            // console.log(e.target.data);
            // console.log(formData)
            console.log(Entity)
            if(Entity === undefined) 
            {
                var msg = 
                {
                  Data: "Entity",
                  Type: "New",
                  Name: formData.name,
                  Speed: formData.speed.toString(),
                  Course: formData.course.toString(),
                  Position: formData.position,
                  Height: formData.height,
                  SetPosition: true
              
                }

            }else {
                var setPos;
                if(PositionDragged === true)
                  {
                     setPos = true;    
                  }else{
                     setPos = false;     
                  }

                var msg = 
                {
                  Data: "Entity",
                  Type: "Update",
                  ID: Entity.id,
                  Speed: formData.speed.toString(),
                  Course: formData.course.toString(),
                  Position: formData.position,
                  Height: formData.height,
                  SetPosition: setPos
              
                }

            }
            console.log(JSON.stringify(msg));

            props.Client.send(JSON.stringify(msg));
            // alert(`Course: ${formData.course}`);
                }
    // console.log(Entity)
    // console.log(EntityOnFocus)
    return (

    <div>
    <div><button onClick={ emptyForm}> New</button>    </div>

    <form onSubmit={handleSubmit}>
        <div className="ControlsComponent">
        <div class="parent">
            <div class="div1"> 
                <div  className="ControlLineHeader">
                
                <InputGroup className="mb-3">
                    <InputGroup.Text id="basic-addon1">Kind</InputGroup.Text>
                        <Form.Select name="Kind"  size="sm" > 
                            <option selected value="plattform"> Plattform</option>
                        </Form.Select>                
                </InputGroup>

                </div>
            </div>
            <div class="div2">
                <div  className="ControlLineHeader">
                {/* <div className="LineHeader">Domain:</div>
                <select name="domain"> 
                    <option name="surface">Surface</option>

                </select> */}

                <InputGroup className="mb-3">
                    <InputGroup.Text id="basic-addon1">Domain</InputGroup.Text>                   
                    <Form.Select name="Domain"  > 
                        <option selected value="Surface"> Surface</option>
                    </Form.Select>
                </InputGroup>
               
                </div>
            </div>
            <div class="div3"> 
            <InputGroup className="mb-3">
                    <InputGroup.Text id="basic-addon1">Type</InputGroup.Text>                   
                    <Form.Select name="Domain" > 
                        <option selected value="F124"> F124</option>
                    </Form.Select>
                </InputGroup>
            </div>
            <div class="div4"> 
            <InputGroup className="mb-3">
                <InputGroup.Text id="basic-addon1">Name</InputGroup.Text>
                <Form.Control
                name="Name"
                placeholder="Name"
                aria-label="Name"
                aria-describedby="basic-addon1"
                value={formData.name} 
                onChange={handleNameInput}
                />
            {/* <input  name="Name"  type="text" onChange={handleNameInput} value={formData.name}   /> */}
            </InputGroup>

                {/* <div class="NameInput">
                <div className="ControlLineHeader">Name:</div>
                </div> */}
            
            </div>
            <div class="div5"> 

            <div class="input-group mb-3">
                <span class="input-group-text">Course</span>        
                    <input className="EntityinputField" name="Course" readOnly={false} type="text"   onClick={handleClick} onChange={handleCourseInput}  value={formData.course}   />

            </div>
                
            </div>
            <div class="div6">
                <div class="input-group mb-3">
                    <span class="input-group-text">Speed</span>
                    <input className="EntityinputField" name="Speed"  onChange={handleSpeedInput}    value={formData.speed} />
                </div> 
            </div>
            <div class="div7"> 
                <div class="input-group mb-3 NumberInputsGroup">
                    <span class="input-group-text">Lat</span>
                    <input className="ControlInput NumberInputs" name="Lat" type="text"   onChange={handleInput}    value={formData.position[0]} />
                </div>
            </div>
            <div class="div8"> 
            <div class="input-group mb-3 NumberInputsGroup" >
                    <span class="input-group-text">Lon</span>
                    {/* <input className="ControlInput" name="Lat" readOnly={true} type="text"  onClick={handleClick}     value={formData.position[0]} /> */}
                    <input className="ControlInput NumberInputs" name="Lon" readOnly={true} type="text"  onClick={handleClick}  onChange={handleInput}   value={formData.position[1]}/>
                </div>
                {/* <div  className="flex">
                    <div className="ControlHeader">Lon:</div>
                </div> */}
            </div>
            <div class="div9"> 
            <div class="input-group mb-3 NumberInputsGroup">
                    <span class="input-group-text">Height</span>
                    {/* <input className="ControlInput" name="Lat" readOnly={true} type="text"  onClick={handleClick}     value={formData.position[0]} /> */}
                    <input className="ControlInput NumberInputs" name="Height" readOnly={true} type="text"  onClick={handleClick}  onChange={handleInput}   value={formData.height}/>
                </div>
                    {/* <div className="ControlHeader">Height:</div>
                 <div  className="flex">
                </div> */}
            </div>
        </div>

        <div> <button type='submit'>Save</button> </div>

        </div>
    </form>
    <button onClick={resetForm}> RESET</button>
    </div>
    );
}

export default EntityControl;