import { Component, Vue, Prop, toNative } from 'vue-facing-decorator';
// import AuthLayout from '@/Layouts/Auth.vue';
import LayoutAuthenticated from '@/Layouts/LayoutAuthenticated.vue';
import { useForm, InertiaForm, Head } from '@inertiajs/vue3';
import FormInput from '@/Components/FormInput.vue'; //          @/Components/FormInput.vue'
import { Dataset, Title, Subject } from '@/Dataset';
import { stardust } from '@eidellev/adonis-stardust/client';

import FormField from '@/Components/FormField.vue';
import FormControl from '@/Components/FormControl.vue';
import SectionMain from '@/Components/SectionMain.vue';
import SectionTitleLineWithButton from '@/Components/SectionTitleLineWithButton.vue';
import FormCheckRadioGroup from '@/Components/FormCheckRadioGroup.vue';
import BaseButton from '@/Components/BaseButton.vue';
import BaseButtons from '@/Components/BaseButtons.vue';
import BaseDivider from '@/Components/BaseDivider.vue';
import CardBox from '@/Components/CardBox.vue';
import MapComponent from '@/Components/Map/map.component.vue';
import SearchAutocomplete from '@/Components/SearchAutocomplete.vue';
import TablePersons from '@/Components/TablePersons.vue';
import TableKeywords from '@/Components/TableKeywords.vue';
import FormValidationErrors from '@/Components/FormValidationErrors.vue';
import FileUploadComponent from '@/Components/FileUpload.vue';
import { MapOptions } from '@/Components/Map/MapOptions';
// import { LatLngBoundsExpression } from 'leaflet/src/geo/LatLngBounds.js';
import { LatLngBoundsExpression } from 'leaflet';
import { LayerOptions } from '@/Components/Map/LayerOptions';

import {
    mdiImageText,
    mdiArrowLeftBoldOutline,
    mdiPlusCircle,
    mdiFinance,
    mdiTrashCan,
    mdiBookOpenPageVariant,
    mdiEarthPlus,
} from '@mdi/js';
import { notify } from '@/notiwind';

export interface IErrorMessage {
    [key: string]: Array<string>;
}

@Component({
    name: 'EditComponent',
    components: {
        LayoutAuthenticated,
        FormInput,
        Head,
        FormField,
        FormControl,
        SectionMain,
        SectionTitleLineWithButton,
        FormCheckRadioGroup,
        BaseButton,
        BaseButtons,
        BaseDivider,
        CardBox,
        MapComponent,
        SearchAutocomplete,
        TablePersons,
        TableKeywords,
        FormValidationErrors,
        FileUploadComponent,
    },
})
class EditComponent extends Vue {
    // Component Property
    @Prop({ type: Object, default: () => ({}) })
    public errors: IErrorMessage;

    @Prop({ type: Object, default: () => ({}) })
    public licenses;

    @Prop({ type: Object, default: () => ({}) })
    public languages;

    @Prop({ type: Object, default: () => ({}) })
    public doctypes;

    @Prop({ type: Object, default: () => ({}) })
    public titletypes;

    @Prop({ type: Object, default: () => ({}) })
    public projects;

    @Prop({ type: Object, default: () => ({}) })
    public descriptiontypes;

    @Prop({ type: Object, default: () => {} })
    public contributorTypes;

    @Prop({ type: Object, default: () => ({}) })
    public subjectTypes;

    @Prop({ type: Object, default: () => ({}) })
    public referenceIdentifierTypes;

    @Prop({ type: Object, default: () => ({}) })
    public relationTypes;

    @Prop({ type: Object, default: () => ({}) })
    public dataset: Dataset;

    // @Prop({
    //     type: Object,
    //     default: () => ({}),
    // })
    // public datasetHasLicenses;

    // Data Property
    // public form: InertiaForm<Dataset>; // = useForm<Dataset>(this.dataset as Dataset);

    // public form : InertiaForm<Dataset>= useForm<Dataset>([]);

    // @Setup(() => useForm<Dataset>(this.dataset as Dataset))
    public form: InertiaForm<Dataset>;

    // @Hook
    created() {
        this.form = useForm<Dataset>(this.dataset as Dataset);
        // this.form.licenses = this.datasetHasLicenses;
        this.form.uploads = [];
    }

    public mapOptions: MapOptions = {
        center: [48.208174, 16.373819],
        zoom: 3,
        zoomControl: false,
        attributionControl: false,
    };
    public baseMaps: Map<string, LayerOptions> = new Map<string, LayerOptions>();
    public fitBounds: LatLngBoundsExpression = [
        [46.4318173285, 9.47996951665],
        [49.0390742051, 16.9796667823],
    ];
    public mapId = 'test';
    mdiImageText = mdiImageText;
    mdiArrowLeftBoldOutline = mdiArrowLeftBoldOutline;
    mdiPlusCircle = mdiPlusCircle;
    mdiFinance = mdiFinance;
    mdiTrashCan = mdiTrashCan;
    mdiBookOpenPageVariant = mdiBookOpenPageVariant;
    mdiEarthPlus = mdiEarthPlus;
    stardust = stardust;

    // mounted() {
    //     this.form = useForm<Dataset>(this.dataset as Dataset);// Initialize myData with the value of propValue
    //   }

    // public results: Array<any> = [];

    // Component method
    public async submit(): Promise<void> {
        let route = this.stardust.route('dataset.update', [this.dataset.id]);
        // await Inertia.post('/app/register', this.form);
        // await router.post('/app/register', this.form);

        if (this.form.licenses.every((item) => this.hasIdAttribute(item))) {
            this.form.licenses = this.form.licenses.map((obj) => obj.id.toString());
        }

        await this.form
            .transform((data) => ({
                ...data,
                licenses: this.form.licenses.every((item) => this.hasIdAttribute(item))
                    ? this.form.licenses.map((obj) => obj.id.toString())
                    : this.form.licenses,
                rights: 'true',
            }))
            .put(route);
    }

    private hasIdAttribute(obj: any): obj is { id: any } {
        return typeof obj === 'object' && 'id' in obj;
    }

    public addTitle(): void {
        const newTitle: Title = { value: '', language: '', type: '' };
        this.form.titles.push(newTitle);
    }
    public removeTitle(key: number): void {
        this.form.titles.splice(key, 1);
    }

    public addDescription(): void {
        const newDescription = { value: '', language: '', type: '' };
        this.form.descriptions.push(newDescription);
    }

    public removeDescription(key: number): void {
        this.form.descriptions.splice(key, 1);
    }

    public onAddAuthor(person) {
        if (this.form.authors.filter((e) => e.id === person.id).length > 0) {
            notify({ type: 'warning', title: 'Warning', text: 'person is already defined as author' }, 4000);
        } else if (this.form.contributors.filter((e) => e.id === person.id).length > 0) {
            notify({ type: 'warning', title: 'Warning', text: 'person is already defined as contributor' });
        } else {
            this.form.authors.push(person);
            notify({ type: 'info', text: 'person has been successfully added as author' });
        }
    }

    public onAddContributor(person) {
        if (this.form.contributors.filter((e) => e.id === person.id).length > 0) {
            notify({ type: 'warning', title: 'Warning', text: 'person is already defined as contributor' }, 4000);
        } else if (this.form.authors.filter((e) => e.id === person.id).length > 0) {
            notify({ type: 'warning', title: 'Warning', text: 'person is already defined as author' }, 4000);
        } else {
            // person.pivot = { contributor_type: '' };
            // // person.pivot = { name_type: '', contributor_type: '' };
            this.form.contributors.push(person);
            notify({ type: 'info', text: 'person has been successfully added as contributor' }, 4000);
        }
    }

    public addKeyword() {   
        let newSubject: Subject = { value: 'test', language: '', type: 'uncontrolled', dataset_count: 0 };
        //this.dataset.files.push(uploadedFiles[i]);
        this.form.subjects.push(newSubject);
    }

    public addReference() {
        let newReference = { value: '', label: '', relation: '', type: '' };
        //this.dataset.files.push(uploadedFiles[i]);
        this.form.references.push(newReference);
    }

    public removeReference(key) {
        this.form.references.splice(key, 1);
    }

    public onMapInitialized(newItem: any): void {
        console.log(newItem);
    }
}

export default toNative(EditComponent);
// export default toNative(EditComponent);
