/*
Пример

result.push(m(ComponentTags, {resource: data.file, typeOf: 'file'}));
*/
function ComponentTags(arguments) {
    let data = {
        resource: null,
        typeOf: null,
        newtag: '',
        groups: {},
        tags_all: [],
        panels: {
            standart: {
                visible: false
            },
            new: {
                visible: false
            }
        },
        error: null,
    };
    for (let key in arguments){
        data[key] = arguments[key];
    };
    function tag_add() {
        /* Добавить тег к ресурсу */
        let newtag = data.newtag.trim().toLowerCase();
        data.newtag = newtag;
        if (data.newtag.length<2) {
            return;
        }
        m.request({
            url: '/api',
            method: "POST",
            body: {
                "jsonrpc": "2.0",
                "method": 'tag.exist',
                "params": {
                    "name": data.newtag
                },
                "id": get_id()
            }
        }).then(
            function(response) {
                if ('result' in response) {
                    tag_add_to_node( response['result'] );
                } else if ('error' in response) {
                    console.log(response);
                    data.panels.new.visible = true;
                }
            }
        ).catch(
            function(error) {
                console.log(error);
            }
        );
    };
    function tag_new_add() {
        /* Добавление нового тега */
        if (data.newtag.length<2) {
            return;
        }
        m.request({
            url: '/api',
            method: "POST",
            body: {
                "jsonrpc": "2.0",
                "method": 'tag.add',
                "params": {
                    "name": data.newtag
                },
                "id": get_id()
            }
        }).then(
            function(response) {
                if ('result' in response) {
                    tags_get();
                    tag_add_to_node( response['result'] );
                }
            }
        );
    };
    function tag_remove(tag) {
        /* Удаление тега из ресурса */
        console.log(tag_includes(tag));
        m.request({
            url: '/api',
            method: "POST",
            body: {
                "jsonrpc": "2.0",
                "method": `tag.${data.typeOf}.delete`,
                "params": {
                    "tag": tag.id,
                    "id": data.resource.id
                },
                "id": get_id()
            }
        }).then(
            function(response) {
                if ('result' in response) {
                    data.resource.tags = arrayRemove(data.resource.tags, tag);
                }
            }
        )
    };
    function tags_get() {
        /* Получить список тегов */
        m.request({
            url: '/api',
            method: "POST",
            body: [
                {
                    "jsonrpc": "2.0",
                    "method": 'tags.groups',
                    "params": {},
                    "id": get_id()
                },
                {
                    "jsonrpc": "2.0",
                    "method": 'tags',
                    "params": {},
                    "id": get_id()
                }
            ]
        }).then(
            function(response) {
                if ('result' in response[0]) {
                    data.groups = response[0]['result'];
                }
                if ('result' in response[1]) {
                    data.tags_all = response[1]['result'];
                }
            }
        )
    };
    function tags_filtered() {
        let result = data.tags_all.filter(filterTag);
        return result;
    };
    function tag_includes(tag) {
        let result = data.resource.tags.find(function(element, index, array) {
            return element.id===tag.id;
        }, tag);
        return result;
    };
    function filterTag(tag) {
        let value = data.newtag;
        if ( value.length<2 ) {
            return false;
        }
        if ( tag.name.toLowerCase().includes(value.toLowerCase()) ) {
            return true;
        }
        return false;
    };
    function tag_add_to_node(tag) {
        /* Добавление тега к ресурсу */
        m.request({
            url: '/api',
            method: "POST",
            body: {
                "jsonrpc": "2.0",
                "method": `tag.${data.typeOf}.add`,
                "params": {
                    "id": data.resource.id,
                    "tag": tag.id
                },
                "id": get_id()
            }
        }).then(
            function(response) {
                if ('result' in response) {
                    data.resource.tags.push(response['result']);
                    sortedTags();
                    data.panels.new.visible = false;
                }
            }
        )
    };
    function sortedTags() {
        if (data.resource.tags === undefined) {return [];}
        data.resource.tags.sort(
            function(a, b) {
                if (a.name > b.name) {
                    return 1;
                }
                if (a.name < b.name) {
                    return -1;
                }
                return 0;
            }
        );
    };
    function newtag_clear() {
        /* Очистка поля нового тега */
        data.newtag = '';
        data.panels.new.visible = false;
    };
    function form_submit_tag_add(e) {
        e.preventDefault();
        tag_add();
    };
    function form_submit_cancelNewTag(e) {
        e.preventDefault();
        newtag_clear();
    };
    function groups_render() {
        let result = [];
        Object.keys(data.groups).forEach(
            function(group, groupIdx) {
                if (groupIdx % 2) {
                    result.push(m('a', {class: 'btn btn-outline-secondary font-monospace btn-lg me-2 mb-2', href: `#tag${groupIdx}`}, group));
                } else {
                    result.push(m('a', {class: 'btn btn-outline-primary font-monospace btn-lg me-2 mb-2', href: `#tag${groupIdx}`}, group));
                };
            }
        );
        return result;
    };
    function groups_tags_render() {
        let result = [];
        Object.keys(data.groups).forEach(
            function(group, groupIdx) {
                let tags = data.groups[group].map(
                    function(tag, tagIdx) {
                        if (tag_includes(tag)) {
                            return m('button', {type: 'button', class: 'btn btn-primary font-monospace me-2 mb-1', onclick: function() {tag_remove(tag)}}, tag.name);
                        } else {
                            return m('button', {type: 'button', class: 'btn btn-outline-secondary font-monospace me-2 mb-1', onclick: function() {tag_add_to_node(tag)}}, tag.name);
                        }
                    }
                );
                result.push(m('div', {class: 'row mt-3'},
                    m('div', {class: 'col pe-0'}, [
                        m('a', {name: `tag${groupIdx}`}),
                        m('a', {class: 'btn btn-outline-danger me-2 mb-1', href: '#tags'}, group),
                        [...tags]
                    ])
                ));
            }
        );
        return result;
    };
    function tags_render() {
        let result = data.resource.tags.map(
            function(tag) {
                return m('div', {class: 'btn-group mb-1 me-2'}, [
                    m(m.route.Link, {class: 'btn btn-outline-secondary font-monospace', href: `/tag/${tag.id}`}, tag.name),
                    m('button', {class: 'btn btn-outline-danger', type: 'button', onclick: function() {tag_remove(tag)}}, m('i', {class: 'fa fa-remove'})),
                ]);
            }
        );
        return result;
    };
    function button_add_render() {
        if (data.panels.standart.visible) {
            return m('button', {class: 'btn btn-outline-danger mb-1 me-2', type: 'button', onclick: function() {panel_show(data.panels.standart)}}, m('i', {class: 'fa fa-minus'}));
        } else {
            return m('button', {class: 'btn btn-outline-success mb-1 me-2', type: 'button', onclick: function() {panel_show(data.panels.standart)}}, m('i', {class: 'fa fa-plus'}));
        }
    };
    return {
        data: data,
        oninit: function(vnode) {
            console.log('ComponentTags.oninit');
            for (let key in vnode.attrs){
                data[key] = vnode.attrs[key];
            };
            tags_get();
        },
        onbeforeupdate: function(vnode) {
            console.log('ComponentTags.onbeforeupdate');
            for (let key in vnode.attrs){
                data[key] = vnode.attrs[key];
            };
            // tags_get();
        },
        view: function(vnode) {
            console.log('ComponentTags.view');
            let result = []
            if (data.resource) {
                result.push(
                    m('div', {class: 'row mb-3'},
                        m('div', {class: 'col'}, [
                            m('a', {name: "tags"}),
                            m('div', {class: 'btn mb-1'}, m('i', {class: 'fa fa-tags'})),
                            button_add_render(),
                            tags_render()
                        ])
                    )
                );
                if (data.panels.standart.visible) {
                    result.push(...[
                        m('div', {class: 'row mb-3'},
                            m('div', {class: 'col'}, [
                                m('form', {onsubmit: form_submit_tag_add},
                                    m('div', {class: 'input-group'}, [
                                        m('button', {class: 'btn btn-outline-danger', type: 'button', onclick: newtag_clear}, m('i', {class: 'fa fa-remove'})),
                                        m('input', {class: 'form-control', oninput: function(e) {data.newtag = e.target.value}, onkeyup: function(e) { if (e.keyCode==13) { tag_add() }}, value: data.newtag}),
                                        m('button', {class: 'btn btn-outline-success', type: 'submit'}, m('i', {class: 'fa fa-save'})),
                                    ])
                                )
                            ])
                        ),
                        m('div', {class: 'row mb-3'},
                            m('div', {class: 'col py-2'},
                                (function() {
                                    let result = tags_filtered().map(
                                        function(tag) {
                                            if (tag_includes(tag)) {
                                                return m('button', {class: 'btn btn-primary font-monospace me-2 mb-1', type: 'button', onclick: function() { tag_remove(tag) }}, tag.name);
                                            } else {
                                                return m('button', {class: 'btn btn-outline-secondary font-monospace me-2 mb-1', type: 'button', onclick: function() { tag_add_to_node(tag) }}, tag.name);
                                            }
                                        }
                                    );
                                    return result;
                                })()
                            )
                        ),
                        m('div', {class: 'row mb-3'},
                            m('div', {class: 'col py-2'},
                                groups_render()
                            )
                        )
                    ]);
                    if (data.panels.new.visible) {
                        result.push(
                            m('form', {onsubmit: form_submit_cancelNewTag},
                                m('div', {class: 'row mb-3'},
                                    m('div', {class: 'col py-2'}, [
                                        m('label', 'Добавить новый тег?'),
                                        m('div', {class: 'row'},
                                            m('div', {class: 'col py-2'},
                                                m('div', {class: 'input-group'}, [
                                                    m('button', {class: 'btn btn-outline-danger', type: 'submit'}, m('i', {class: 'fa fa-close'})),
                                                    m('input', {class: 'form-control', oninput: function (e) {data.newtag = e.target.value}, value: data.newtag}),
                                                    m('button', {class: 'btn btn-outline-success', type: 'button', onclick: tag_new_add}, 'Добавить')
                                                ])
                                            )
                                        )
                                    ])
                                )
                            ),
                        );
                    };
                    result.push(
                        groups_tags_render()
                    );
                };
            };
            return result;
        }
    };
};
