import { bind } from "astal";
import AstalBluetooth from "gi://AstalBluetooth";

const BTDevice = ({ device }: { device: AstalBluetooth.Device }) => {
    return (
        <button
            visible={bind(device, "name").as(n => n !== null)}
            child={
                <centerbox
                    startWidget={
                        <box>
                            <image
                                iconName={"chronometer-reset"}
                                tooltipText={"Device is currently connecting"}
                                visible={bind(device, "connecting")}
                            ></image>
                            <image
                                iconName={bind(device, "icon")}
                                marginEnd={3}
                            ></image>
                        </box>
                    }
                    centerWidget={
                        <label
                            label={bind(device, "name").as(n => n ?? "No name")}
                            marginEnd={5}
                        ></label>
                    }
                    endWidget={
                        <box>
                            <label
                                label={bind(device, "batteryPercentage").as(
                                    bat => (bat >= 0 ? bat + "%" : "?%"),
                                )}
                                tooltipText={"Device's battery percentage"}
                                marginEnd={3}
                            ></label>
                            <image
                                iconName={bind(device, "paired").as(v =>
                                    v ? "network-bluetooth-activated-symbolic" : "bluetooth-disconnected-symbolic",
                                )}
                            ></image>
                            <button tooltipText={"Device trusted status"} child={
                                <image
                                    iconName={bind(device, "trusted").as(v =>
                                        v ? "checkbox" : "window-close-symbolic",
                                    )}
                                ></image>
                            } onClicked={() => device.set_trusted( !device.get_trusted() )}
                            cssClasses={[ 'button-no-margin' ]}
                            ></button>
                        </box>
                    }
                ></centerbox>
            }
            onClicked={() => {
                connectOrPair( device );
            }}
        ></button>
    );
};

const connectOrPair = (device: AstalBluetooth.Device) => {
    if ( device.get_paired() ) {
        device.connect_device(() => { });
        // Show failed message if tried to connect and failed
    } else {
        device.pair();
    }
};

export default BTDevice;
