'use strict';

import { FBLang } from './lang.js';

export function App(module_settings, fb_data) {
    let settings = {
            accessToken: module_settings?.accessToken || {token:"",date:""},
            user_id: module_settings?.user_id || "",
            forms: module_settings?.forms || [],
            cron_task: module_settings?.cron_task || 0
        };

    let name = fb_data?.name || "",
        auth = fb_data?.id != "" ? true : false;

    let fb_lang = config['lang'] == 'russian'
        ? (FBLang())['russian']
        : (FBLang())['english']
    ;

    function genid() {
        var dt = new Date().getTime();
        var mask = 'ixxxyxxx';  //'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
        return mask.replace(/[xy]/g, function(c) {
            var r = (dt + Math.random()*16)%16 | 0;
            dt = Math.floor(dt/16);
            return (c=='x' ? r :(r&0x3|0x8)).toString(36);
        });
    }

    function FacebookButton() {
        async function setData(data) {
            if (data?.error) {
                return;
            }
            if(data.id && data.id.length !== 0){
                auth = true;
                settings.user_id = settings.user_id.length === 0 || settings.user_id == 0 ? data.id : settings.user_id;
            }
            else {
                auth = false;
            }
            settings.accessToken.token = (
                data.authResponse &&
                data.authResponse.accessToken.length !== 0 &&
                settings.accessToken.token.length === 0
            ) ? data.authResponse.accessToken : settings.accessToken.token;
            name = data?.name || "";
            m.redraw();
        }

        const checkLoginState = (callback) => (e) => {
            FB.getLoginStatus(response => {
                callback(response);
                if(response.status != "unknown") {
                    FB.api('/me', response => {
                        callback(response);
                    });
                }
            })
        }

        return {
            oncreate: async function() {
                await FB.init({
                    appId  : '229731955267375',
                    cookie : true,
                    xfbml  : true,
                    version: 'v10.0'
                });
                checkLoginState(setData)();
            },
            view: function() {
                return [
                    m('div', {
                        class: 'facebook_lead_ads__login',
                        style: 'display: flex;justify-content: center;'
                    }, auth ? m('button', {
                        class: 'btn btn-default btn-sm',
                        onclick: async function() {
                            await FB.logout();
                            window.location.reload();
                        }
                    }, fb_lang['log_in'] + name) : m('button', {
                        class: 'btn btn-default btn-sm',
                        onclick: function() {
                            FB.login(checkLoginState(setData), {
                                scope: 'ads_management,leads_retrieval,pages_show_list,pages_read_engagement,'
                                        +'pages_manage_metadata,pages_manage_ads,business_management,public_profile'
                            });
                        }
                    }, fb_lang['continue_with_fb']))
                ];
            },
        };
    }

    function Select(){
        return {
            oncreate: function (vnode) {
                if(!vnode.attrs.class || vnode.attrs.class && vnode.attrs.class.match('dont_use_chosen') === null){
                    $(vnode.dom).find('select').chosen();
                }
            },
            onupdate: function (vnode) {
                $(vnode.dom).find('select').chosen('destroy');
                if(!vnode.attrs.class || vnode.attrs.class && vnode.attrs.class.match('dont_use_chosen') === null){
                    $(vnode.dom).find('select').chosen();
                }
            },
            onremove: function (vnode) {
                if(!vnode.attrs.class || vnode.attrs.class && vnode.attrs.class.match('dont_use_chosen') === null){
                    $(vnode.dom).find('select').chosen('destroy');
                }
            },
            view: function(vnode){
                return m('span', {}, m('select', {
                    class: vnode.attrs.class || '',
                    style: vnode.attrs.style || '',
                    value: vnode.attrs.value,
                    onchange: vnode.attrs.onchange || ''
                }, vnode.children));
            }
        }
    }

    function Input(){
        return {
            view: function(vnode){
                return m('input', {
                    type: vnode.attrs.type,
                    class: vnode.attrs.class || "",
                    style: vnode.attrs.style || "",
                    placeholder: vnode.attrs.placeholder || "",
                    onclick: vnode.attrs.onclick ? vnode.attrs.onclick : null,
                    onkeydown: vnode.attrs.onkeydown ? vnode.attrs.onkeydown : null,
                    oninput: vnode.attrs.oninput ? vnode.attrs.oninput : null,
                    onchange: vnode.attrs.onchange ? vnode.attrs.onchange : null,
                    value: vnode.attrs.value || "",
                    disabled: vnode.attrs.disabled,
                }, vnode.children)
            }
        }
    }

    function Settings() {
        let show = null;
        let metadata = {};

        function formComponent() {
            return {
                view: function(vnode) {
                    let item = vnode.attrs.item;

                    return m('table', { style: 'margin: 0 auto;' }, [
                        m('tr', {}, [
                            m('td', { style: 'width: 35%;', align: 'right' }, m('span', {}, fb_lang['form_name'])),
                            m('td', { style: 'width: 65%;' }, m(Input, {
                                type: 'text',
                                class: 'form-control form-control-250',
                                oninput: function(e) { item.formName = e.target.value; },
                                onchange: function(e) { item.formName = e.target.value; },
                                value: item?.formName || ""
                            }))
                        ]),
                        m('tr', {}, [
                            m('td', { style: 'width: 35%;', align: 'right' }, m('span', {}, fb_lang['form_id'])),
                            m('td', { style: 'width: 65%;' }, m(Input, {
                                type: 'text',
                                class: 'form-control form-control-250',
                                oninput: function(e) { item.formId = e.target.value; },
                                onchange: function(e) { item.formId = e.target.value; },
                                value: item?.formId || ""
                            }))
                        ]),
                        m('tr', {}, [
                            m('td', { style: 'width: 35%;', align: 'right' }, m('span', {}, fb_lang['table'])),
                            m('td', { style: 'width: 65%;' }, m(Select, {
                                class: 'form-control form-control-250',
                                onchange: function(e) {
                                    item.tableId = e.target.value;
                                    item.fields = e.target.value == 0 ? [] : [{description: "ID", cbFieldId: 0, default: ""}];
                                }
                            }, [
                                m('option', {
                                    value: 0,
                                    selected: (item.tableId == 0)
                                }, ''),
                                Object.keys(metadata?.tables || {}).map(function(key) {
                                    return m('option', {
                                        value: metadata.tables[key]['id'],
                                        selected: (metadata.tables[key]['id'] == item.tableId)
                                    }, metadata.tables[key]['name'])
                                })
                            ]))
                        ]),
                        m('tr', {}, m('td', {}, m('div', { style: 'height: 20px' }, ''))),
                        m('tr', {},
                            m('td', { colspan: 2 }, m('table', {
                                style: 'margin: auto'
                            },
                            m('tr', {}, [
                                m('th', { style: 'font-weight: bold; padding: 3px 5px; font-size: 110%' }, ''),
                                m('th', { style: 'font-weight: bold; padding: 3px 5px; font-size: 110%' }, fb_lang['fb_field']),
                                m('th', { style: 'font-weight: bold; padding: 3px 5px; font-size: 110%' }, fb_lang['cb_field']),
                                m('th', { style: 'font-weight: bold; padding: 3px 5px; font-size: 110%' }, fb_lang['def_val']),
                            ]),
                            (item?.tableId == 0
                                ? null
                                : item?.fields.map(function(elem) {      /** OTHER FIEILD */
                                    let fields = metadata?.fields[item.tableId];
                                    return m('tr', [
                                        m('td', {}, elem.description == 'ID'
                                            ? ''
                                            : m('a', m('img[src=images/b_drop.png]', {
                                                onclick: function() { item.fields = item.fields.filter(i => elem !== i); },
                                                style: {padding: '0 3px 2px 0'}
                                            }))),
                                        m('td', {}, m(Input, {
                                            type: 'text',
                                            class: 'form-control form-control-160',
                                            oninput: function(e) { elem.description = e.target.value; },
                                            onchange: function(e) { elem.description = e.target.value; },
                                            value: elem.description,
                                            disabled: (elem.description == 'ID')
                                        })),
                                        m('td', {}, m(Select, {
                                            class: 'form-control form-control-160',
                                            onchange: function(e) { elem.cbFieldId = e.target.value; }
                                        }, [
                                            m('option', {
                                                value: 0,
                                                selected: (elem.cbFieldId == 0)
                                            }, ''),
                                            Object.keys(fields).map(function(cbField) {
                                                if (cbField == 'id' || cbField == 'user_id' || cbField == 'add_time' || cbField == 'status') {
                                                    return null;
                                                }
                                                return m('option', {
                                                    value: fields[cbField]['id'],
                                                    selected: (fields[cbField]['id'] == elem.cbFieldId)
                                                }, fields[cbField]['name'])
                                            })
                                        ])),
                                        m('td', {}, elem.description == 'ID'
                                            ? null
                                            : m(Input, {
                                                type: 'text',
                                                class: 'form-control form-control-160',
                                                oninput: function(e) { elem.default = e.target.value; },
                                                onchange: function(e) { elem.default = e.target.value; },
                                                value: elem.default
                                            })),
                                    ]);
                                })),
                        ))),
                        item?.tableId == 0
                            ? null
                            : m('tr', {}, m('td', { colspan: 2 }, m('span', {
                                style: "cursor:pointer;text-decoration:underline;text-decoration-style:dotted;color:blue;font-size:13px;padding-left:30px;user-select:none;",
                                onclick: function() {
                                    item.fields.push({description: "", cbFieldId: 0, default: ""});
                                }
                            }, fb_lang['add_field'])))
                    ])
                }
            }
        }

        return {
            oncreate: async function() {
                let response = await fetch("api/dev/metadataset", {
                    method: 'GET',
                    credentials: "include",
                    headers: {
                        'X-Auth-Token' : window.x_auth_token || null
                    }
                });
                response = await response.json();
                // console.log(response);
                metadata = response || {};
            },

            view: function(vnode) {
                let set = vnode.attrs.settings || {};

                return [
                    m('table', { style: 'margin: 0 auto; min-width: 650px;' }, [
                        m('tr', {}, m('td', {
                            align: 'center',
                            colspan: 2,
                            style: 'font-size: 120%; font-weight: bold;'
                        }, fb_lang['forms'])),
                        set?.forms.map(function(item) {                             /** FORM LIST */
                            return m('tr', {}, [
                                m('td', { align: 'right', style: 'width: 48%;' },  m('img[src=images/b_drop.png]', {
                                    onclick: function() { set.forms = set.forms.filter(i => item !== i); },
                                    style: {padding: '0 3px 2px 0'}
                                })),
                                m('td', {
                                    align: 'left',
                                    style: 'width: 52%;',
                                }, m('span', {
                                    style: "cursor:pointer;text-decoration:underline;text-decoration-style:dotted;color:blue;font-size:13px;user-select:none;",
                                    onclick: function() { show = show == item.id ? null : item.id; }
                                },
                                item.formName == "" ? fb_lang['un_form'] : item.formName))
                            ]);
                        }) || null,
                        m('tr', {                                                  /** ADD FORM */
                            style: "padding-bottom:25px;text-align:center;"
                        }, m('td', { 'colspan': 2 }, m('span', {
                            style: "cursor:pointer;text-decoration:underline;text-decoration-style:dotted;color:blue;font-size:13px;user-select:none;",
                            onclick: function() {
                                show = genid();
                                set.forms.push({id: show, formName: "", formId: "", tableId: 0, fields: []});
                            }
                        }, fb_lang['add']))),
                        m('tr', {}, m('td', {}, m('div', { style: 'height: 20px;' }, ''))),
                        show === null
                            ? null
                            : m('tr', {}, m('td', { colspan: 2}, m(formComponent, {
                                item: set?.forms.filter(item => show == item.id)[0] || null
                            })))
                    ])
                ];
            },
        }
    }

    return {
        view: function() {
            return [
                m(FacebookButton),
                m('hr'),
                m(Settings, { settings }),
                m('div', {                                                          /** SAVE BUTTON */
                    style: 'display: flex;justify-content: center;'
                }, m('button', {
                    class: 'btn btn-default btn-sm',
                    onclick: async function() {
                        // console.log(settings);
                        settings.accessToken.date = '';
                        let response = await fetch("./api/dev/settings/cbext.clientbase.fb_lead", {
                            method: 'PATCH',
                            credentials: "include",
                            headers: {
                                'X-Auth-Token' : window.x_auth_token,
                                'Content-Type': 'application/vnd.api+json'
                            },
                            body: JSON.stringify({
                                data: {
                                    type: 'settings',
                                    id: 'cbext.clientbase.fb_lead',
                                    attributes: { value: settings }
                                }
                            }, null, 4)
                        });

                        response = await response.json();
                        if (response?.data?.attributes?.value) {
                            displayNotification('Settings have been saved.', 1);
                            window.location.reload();
                        } else {
                            displayNotification('Settings not saved.', 2);
                        }
                    }
                }, lang['Save']))
            ]
        }
    };
}
