import * as React from 'react';
import { useField } from "formik";
import { Observable } from '../../../auto/js/events/Observable';
import { geoMetadataLoader } from '../../../auto/js/metadata/GeoMetadataLoader';
import { AutoCompleteInput } from '../../../auto/js/widgets';
import { t } from '../../../auto/js/services';

const provinceObservable = new Observable();
const zoneObservable = new Observable();
const districtObservable = new Observable();
const islandObservable = new Observable();

export function AddressComponent (props) {
    const [field, meta, helpers] = useField(props.name);
    const { value } = meta;
	const { setValue } = helpers;

    const handleProvinceChange = (value) => {
        provinceObservable.publish(geoMetadataLoader.getChilds(value.key))
        setValue(value.key);
    }
    const handleZoneChange = (value) => {
        zoneObservable.publish(geoMetadataLoader.getChilds(value.key))
        setValue(value.key);
    }
    const handleDistrictChange = (value) => {
        districtObservable.publish(geoMetadataLoader.getChilds(value.key))
        setValue(value.key);
    }
    const handleIslandChange = (value) => {
        islandObservable.publish(geoMetadataLoader.getChilds(value.key))
        setValue(value.key);
    }
    const handleLocationChange = (value) => {
        setValue(value.key);
    }
    console.log(value)
    console.log(props.data)
    return (
        <>
        <h2>{props.name}</h2>
        <AutoCompleteInput name={"province"} options={() => geoMetadataLoader.getChilds(geoMetadataLoader.rootid)} label={t`Province`} handleChange={(data) => handleProvinceChange(data)} />
        <AutoCompleteInput name={"zone"} options={() => ""} label={t`Area Council`} handleChange={(data) => handleZoneChange(data)} observable={provinceObservable} />
        <AutoCompleteInput name={"distric"} options={() => ""} label={t`District`} handleChange={(data) => handleDistrictChange(data)} observable={zoneObservable} />
        <AutoCompleteInput name={"island"} options={() => ""} label={t`Island`} handleChange={(data) => handleIslandChange(data)} observable={districtObservable} />
        <AutoCompleteInput name={"location"} options={() => ""} label={t`Location`} handleChange={(data) => handleLocationChange(data)} observable={islandObservable} />
        </>
    )
}