import React, { useContext, useState } from 'react'
import { Link } from 'react-router-dom';
import { UserCtx, UserCtxT, DogT, Axios, ResponseT, TUser } from '../context/UserContext';
import Checkbox from './Checkbox';
import Img from './Img';
import './Qr.css';

type ListItemT = 
{
    name: string;
    ordernum: number;
}


export default function Qr() 
{
    const { user } = useContext<UserCtxT | null>(UserCtx) as UserCtxT;
    const [dog, setDog] = useState<DogT | any>({}); // local dog not the dog in UserContext
    const [fontSize, setFontSize] = useState(100);
    const [visibleItem, setVisibleItem] = useState(0b111); // 100 name, 10 phone, 1 email
    const [itemOrder, setItemOrder] = useState(123); //  name first, phone second, email third
    const [itemList, setItemList] = useState([
                                                {name:'Name', ordernum: 1},
                                                {name:'Telefon', ordernum: 2},
                                                {name:'Email', ordernum: 3}
                                             ]);
    //save reference for dragItem and dragOverItem
    const dragItem = React.useRef<any>(null);
    const dragOverItem = React.useRef<any>(null);

    function incrementFontSize()  
    {
        if(fontSize < 200)
        {
            setFontSize(fontSize + 1);
        }
    }

    function decrementFontSize() 
    {
        if(fontSize > 1)
        {
            setFontSize(fontSize - 1);
        }
    }

    function setBitField(val: number, checked: boolean, bit: number) : number
    {
        if(checked)
        {
            val |= bit;
        }
        else
        {
            val ^= bit;
        }
        return val;
    }

    function checkBoxChange(id: string, checked: boolean) : void
    {
        let value = visibleItem;
        if(id==="name")
        {
            value = setBitField(value, checked, 0b100);
        }
        if(id==="phone")
        {
            value = setBitField(value, checked, 0b010);
        }
        if(id==="email")
        {
            value = setBitField(value, checked, 0b001);
        }
        setVisibleItem(value);
    }

    function getItemOrderNumber(digit: number)
    {
        let ordernum = itemOrder; // 123
        ordernum = ordernum % (digit*10); // 123
        ordernum = Math.trunc(ordernum / digit);

        return ordernum;
    }
	//const handle drag sorting
	function handleSort()
    {
		//duplicate items
		let _itemList = [...itemList];

		//remove and save the dragged item content
		const draggedItemContent = _itemList.splice(dragItem.current, 1)[0];

		//switch the position
		_itemList.splice(dragOverItem.current, 0, draggedItemContent);

		//reset the position ref
		dragItem.current = null;
		dragOverItem.current = null;

		//update the actual array
		setItemList(_itemList);

        // set new itemorder
        let newItemOrder = 0;
        let digit = 100;
		_itemList.map((item, index) => 
        {
            newItemOrder += item.ordernum * digit;
            digit /= 10;
        });
        setItemOrder(newItemOrder);
	}

    if(user && dog.success === undefined)
    {
        Axios.post<ResponseT>('getDog.php', 
        {
            qr_id: user.qr_id
        })
        .then((resDog) =>
        {
            setDog(resDog.data);    
        })
        .catch((err) => console.error(err));
    }

    return (
        <>
            {user && dog.data &&
            <div>
                <h1>Qr-Code Druck</h1>
                <Link to={"/profil"}>Zurück zum Profil</Link>

                <div> 
                    <button onClick={incrementFontSize}>up</button>
                    <div>{fontSize}</div>
                    <button onClick={decrementFontSize}>down</button>
                </div>
                <div>
                <Checkbox 
                        id='name' 
                        label={'Name'} 
                        checked={(visibleItem & 0b100) > 0} 
                        changeEvent={checkBoxChange}
                        />
                    <Checkbox 
                        id='phone' 
                        label={'Telefon'} 
                        checked={(visibleItem & 0b010) > 0} 
                        changeEvent={checkBoxChange}
                        />
                    <Checkbox 
                        id='email' 
                        label={'Email'} 
                        checked={(visibleItem & 0b001) > 0} 
                        changeEvent={checkBoxChange}
                        />
                </div>
                <div className="list-container">
				{itemList.map((item, index) => (
					<div
						key={index}
						className="list-item"
						draggable
						onDragStart={(e) => (dragItem.current = index)}
						onDragEnter={(e) => (dragOverItem.current = index)}
						onDragEnd={handleSort}
						onDragOver={(e) => e.preventDefault()}>
						<h6>{item.name}</h6>
					</div>
				))}
                </div>
                
                <div className='blockRepeat'>
                <div className='qrCodeBackFront'>
                    <div className='qrCode frame'>
                        <div className='qrCode__'>SCAN ME</div>
                        <Img pth={dog.data.qr_code}/>
                    </div>
                    <div className='qrCodeVert frame' style={{ fontSize: fontSize + '%' }}>
                        {((visibleItem & 0b100) > 0) && <div className={`vertFont order${getItemOrderNumber(100)}`}>{dog.data.name}</div>}
                        {((visibleItem & 0b010) > 0) && <div className={`vertFont order${getItemOrderNumber(10)}`}>{dog.data.phone}</div>}
                        {((visibleItem & 0b001) > 0) && <div className={`vertFont order${getItemOrderNumber(1)}`}>{dog.data.email}</div>}
                    </div>
                </div>
                <div className='qrCodeBackFront'>
                    <div className='qrCode frame'>
                        <div className='qrCode__'>SCAN ME</div>
                        <Img pth={dog.data.qr_code}/>
                    </div>
                    <div className='qrCodeVert frame' style={{ fontSize: fontSize + '%' }}>
                        {((visibleItem & 0b100) > 0) && <div className={`vertFont order${getItemOrderNumber(100)}`}>{dog.data.name}</div>}
                        {((visibleItem & 0b010) > 0) && <div className={`vertFont order${getItemOrderNumber(10)}`}>{dog.data.phone}</div>}
                        {((visibleItem & 0b001) > 0) && <div className={`vertFont order${getItemOrderNumber(1)}`}>{dog.data.email}</div>}
                    </div>
                </div>
                <div className='qrCodeBackFront'>
                    <div className='qrCode frame'>
                        <div className='qrCode__'>SCAN ME</div>
                        <Img pth={dog.data.qr_code}/>
                    </div>
                    <div className='qrCodeVert frame' style={{ fontSize: fontSize + '%' }}>
                        {((visibleItem & 0b100) > 0) && <div className={`vertFont order${getItemOrderNumber(100)}`}>{dog.data.name}</div>}
                        {((visibleItem & 0b010) > 0) && <div className={`vertFont order${getItemOrderNumber(10)}`}>{dog.data.phone}</div>}
                        {((visibleItem & 0b001) > 0) && <div className={`vertFont order${getItemOrderNumber(1)}`}>{dog.data.email}</div>}
                    </div>
                </div>


                <div className='qrCodeBackFront'>
                    <div className='qrCode frame'>
                        <div className='qrCode__'>SCAN ME</div>
                        <Img pth={dog.data.qr_code}/>
                    </div>
                    <div className='qrCodeVert frame' style={{ fontSize: fontSize + '%' }}>
                        {((visibleItem & 0b100) > 0) && <div className={`vertFont order${getItemOrderNumber(100)}`}>{dog.data.name}</div>}
                        {((visibleItem & 0b010) > 0) && <div className={`vertFont order${getItemOrderNumber(10)}`}>{dog.data.phone}</div>}
                        {((visibleItem & 0b001) > 0) && <div className={`vertFont order${getItemOrderNumber(1)}`}>{dog.data.email}</div>}
                    </div>
                </div>
                <div className='qrCodeBackFront'>
                    <div className='qrCode frame'>
                        <div className='qrCode__'>SCAN ME</div>
                        <Img pth={dog.data.qr_code}/>
                    </div>
                    <div className='qrCodeVert frame' style={{ fontSize: fontSize + '%' }}>
                        {((visibleItem & 0b100) > 0) && <div className={`vertFont order${getItemOrderNumber(100)}`}>{dog.data.name}</div>}
                        {((visibleItem & 0b010) > 0) && <div className={`vertFont order${getItemOrderNumber(10)}`}>{dog.data.phone}</div>}
                        {((visibleItem & 0b001) > 0) && <div className={`vertFont order${getItemOrderNumber(1)}`}>{dog.data.email}</div>}
                    </div>
                </div>


                <div className='qrCodeBackFront'>
                    <div className='qrCode frame'>
                        <div className='qrCode__'>SCAN ME</div>
                        <Img pth={dog.data.qr_code}/>
                    </div>
                    <div className='qrCodeVert frame' style={{ fontSize: fontSize + '%' }}>
                        {((visibleItem & 0b100) > 0) && <div className={`vertFont order${getItemOrderNumber(100)}`}>{dog.data.name}</div>}
                        {((visibleItem & 0b010) > 0) && <div className={`vertFont order${getItemOrderNumber(10)}`}>{dog.data.phone}</div>}
                        {((visibleItem & 0b001) > 0) && <div className={`vertFont order${getItemOrderNumber(1)}`}>{dog.data.email}</div>}
                    </div>
                </div>
                </div>
            </div> }
            {/* { !dog.data && user &&  
                <>
                    <h1>Qr-Code Druck</h1>
                    <div>Logged in als:</div>
                    <div>{user?.email}</div>
                    <div>{user?.qr_id}</div>
                </>
            } */}
            { !dog.data && !user &&  
                <>
                    <h1>Qr-Code Druck</h1>
                    <div>nothing</div>
                </>
            }
        </>
    )
}
