(function ($) {
    let $$ = Dom7, theme = 'auto', client = {};

    let JF = {};

    JF.BlobSender = function (request, callback) {
        $.ajax({
            url: "core/php/index.php",
            async: true,
            type: "POST",
            data: request,
            success: function (result) {
                callback(result);
            }, error: function (xhr, textStatus, errorThrown) {
                callback(xhr, textStatus, errorThrown);
            }
        });
    };
    JF.LoadData = function (request, json, callback) {

        try {
            $.ajax({
                url: "core/php/index.php",
                async: true,
                type: "POST",
                data: request,
                success: function (result) {
                    if (json !== null)
                        if (json)
                            result = JSON.parse(result);
                    if (callback !== null)
                        if (IsValidJSONString(result)) {
                            callback(result);
                        } else {
                            callback(JSON.parse("[{'error':'1','result':'" + result + "'}]"));
                        }
                }, error: function (xhr, textStatus, errorThrown) {
                    if (callback !== null)
                        callback(xhr);
                }
            });
        }
        catch (err) {
            console.log(err.message);
        }

        /**
         * @return {boolean}
         */
        function IsValidJSONString(data) {
            return true;
            //(/^[\],:{}\s]*$/.test(data.replace(/\\["\\\/bfnrtu]/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, '')));
        }
    };


    if (document.location.search.indexOf('theme=') >= 0) {
        theme = document.location.search.split('theme=')[1].split('&')[0];
    }

    let app = new Framework7({
        id: 'com.android.kashan.card',
        root: '#app',
        theme: theme,

        dialog: {
            // set default title for all dialog shortcuts
            // change default "OK" button text
            buttonOk: 'خب',
            buttonCancel: 'نه',
        }
    });

    let update_image = function (shop_id, base64, name, callback) {
        //JF.BlobSender
        let request = {
            request: 'upload-image',
            name: name,
            shop_id: shop_id,
            base64: base64
        };
        JF.BlobSender(request, function (e) {
            callback(JSON.parse(e), shop_id)
        })
    };


    let login_process = function (title, message, callback) {

        app.dialog.login(message, title, function (username, password) {
            app.dialog.progress("منتظر باشید.");

            let user1 = '', user2 = '';
            if (username.length === 10 || username.length === 11) {
                if (username.length === 10) user2 = 0 + (user1 = username);
                if (username.length === 11) user2 = 0 + (user1 = username.substring(1, username.length));
            }

            if (username.length > 0 && password.length > 0 && (username.length === 11 || username.length === 10) && password.length === 10) {
                JF.LoadData({
                        request: 'query-select',
                        query: "SELECT\n" +
                        "  `ID`, \n" +
                        "  CONCAT(fName, ' ', lName)                    as `full-name`,\n" +
                        "  (SELECT count(ID)\n" +
                        "   FROM app_acceptor_list\n" +
                        "   WHERE profile_id = app_acceptor_profile.ID) as `count`\n" +
                        "FROM `app_acceptor_profile` \n" +
                        "WHERE (pNumber = '" + user1 + "' OR pNumber = '" + user2 + "') AND pNC = '" + password + "'"
                    },
                    true, function (e) {
                        if (e.length === 1) {
                            e = e[0];
                            app.dialog.close();
                            setTimeout(function () {
                                app.dialog.alert("خوش آمدید " + e['full-name'], 'کاشان کارت ', function () {
                                    if (e.count === '0') {
                                        let error = '';
                                        error += 'شما هیچ فروشگاهی برای ویرایش ندارید.';
                                        error += '<br>';
                                        error += 'لطفا با پشتیبانی هماهنگ کنید.';
                                        $$('.demo-facebook-card').removeClass('display-none');
                                        app.dialog.alert(error, 'کاشان کارت ', function () {
                                            $('.page').fadeIn('slow');
                                        });
                                    } else {
                                        $('.page').fadeIn('slow');
                                        //load panel
                                        callback(e.ID, e.count);
                                    }
                                });
                            }, 500);
                        }
                        else {
                            setTimeout(function () {
                                app.dialog.close();
                                login_process(title, message, callback)
                            }, 500);
                        }
                    }
                );
            } else {
                setTimeout(function () {
                    app.dialog.close();
                    login_process(title, message, callback)
                }, 500);
            }
        }, function (username, password) {
            login_process(title, message, callback)
        });
    };

    let create_shop_panel = function (profile_id, shop_id, shop_name, shop_address, limit, index, callback) {
        let html = '';
        html += '<div class="card card-expandable" id="panel-id-' + shop_id + '" style="display: none;">';
        html += '    <div class="card-content">';
        html += '        <div class="bg-color-lime" style="height: 300px">';
        html += '            <div class="card-header text-align-center center-center text-color-black display-block"';
        html += '                 style="padding-top: 100px;">' + shop_name;
        html += '                <br>';
        html += '                <small style="opacity: 0.7">' + shop_address + '</small>';
        html += '            </div>';
        html += '            <a href="#" class="link card-close card-opened-fade-in color-black"';
        html += '               style="position: absolute; right: 15px; top: 15px">';
        html += '                <i class="icon f7-icons">close_round_fill</i>';
        html += '            </a>';
        html += '        </div>';
        html += '        <div class="card-content-padding">';
        html += '            <!-- Slider main container -->';
        html += '           <div class="block">';
        html += '               <div class="row text-align-center header-image-area-' + shop_id + '">';
        html += '                   <div class="elevation-2 col-100 tablet-100 text-color-black margin-top padding">';
        html += '                       <div class="col button-fill color-deeporange">شما میتوانید ' + limit + ' عکس برای این فروشگاه انتخاب کنید.';
        html += '                       </div>';
        html += '                   </div>';
        html += '               </div>';
        html += '               <div class="row text-align-center content-image-area-' + shop_id + '">';
        html += '                   <div class="elevation-2 col-100 tablet-100 text-color-black margin-top padding">';
        html += '                       <span class="progressbar-infinite color-multi"></span>';
        html += '                       <p class="text-align-center" style="width: 100%;">منتظر بمانید</p>';
        html += '                   </div>';
        html += '               </div>';
        html += '               <div class="row text-align-center add-image-area-' + shop_id + '">';
        html += '                   <div class="elevation-2 col-100 tablet-100 text-color-black margin-top padding text-align-center center-center">';
        html += '                       <p>اظافه کردن</p>';
        html += '                       <label for="image-add-' + shop_id + '" class="col button button-fill color-green">';
        html += '                           <i class="f7-icons center-center text-align-center">add</i>';
        html += '                       </label>';
        html += '                       <input data-id="' + shop_id + '" class="display-none img-add" id="image-add-' + shop_id + '" type="file" accept="image/*">';
        html += '                   </div>';
        html += '               </div>';
        html += '           </div>';
        html += '        </div>';
        html += '    </div>';
        html += '</div>';
        let element = $(html);
        $('.page-content').append(element);
        $('#panel-id-' + shop_id).fadeIn((index + 1) * 500, function () {
            callback(profile_id, shop_id, limit, index, element);
        })
    };


    let remove_element = function (img_id, callback) {
        JF.LoadData({
                request: 'delete-image',
                img: img_id
            },
            false, function (e) {
                callback(e, img_id);
            });
    };

    login_process('وارد شوید', 'مشخصات ورود خود را وارد کنید', function (id, count) {
        if (count > 0) {
            let slide = function (image) {
                let html = '';
                html += '<div class="elevation-2 col-50 tablet-50 text-color-black margin-top padding" id="image-' + image.ID + '">';
                html += '   <img src="' + image.imgSrc + '" width="100%">';
                html += '   <p class="row">';
                html += '        <button class="col button button-fill color-red img-remove" data-id="' + image.ID + '">حذف</button>';
                html += '   </p>';
                html += '</div>';
                return html;
            };
            JF.LoadData({
                    request: 'query-select',
                    query:
                    "SELECT\n" +
                    "  `profile_id`                   as `profile_id`,\n" +
                    "  `image_limit`                  as `img_limit`,\n" +
                    "  `app_acceptor_list`.`ID`       as `acceptor_id`,\n" +
                    "  `app_acceptor_list`.`sName`    as `name`,\n" +
                    "  `app_acceptor_list`.`sAddress` as `address`\n" +
                    "FROM `app_acceptor_list`\n" +
                    "WHERE profile_id = " + id + "\n" +
                    "ORDER BY `acceptor_id` ASC"
                },
                true, function (e) {
                    for (let i = 0; i < e.length; i += 1) {
                        let item = e[i];
                        create_shop_panel(
                            item.profile_id,
                            item.acceptor_id,
                            item.name,
                            item.address,
                            item.img_limit,
                            i,
                            function (profile_id, shop_id, limit, index, element) {
                                JF.LoadData({
                                    request: 'select-image',
                                    for: shop_id
                                }, true, function (e) {
                                    let content = $('div.content-image-area-' + shop_id);
                                    content.append().empty();
                                    for (let i = 0; i < e.length; i += 1)
                                        content.prepend(slide(e[i]));


                                    let remove_listener = function () {
                                        $$('.img-remove').off('click').on('click', function (e) {
                                            let item = $$(this);
                                            app.dialog.confirm('این تصویر حذف شود؟', 'اخطار', function () {
                                                //function remove from db
                                                remove_element(item.attr('data-id'), function (e, id) {
                                                    if (e === '1') {
                                                        $$('#image-' + id).animate({'opacity': 0.0}, {
                                                            duration: 500, complete: function (elements) {
                                                                elements.remove();
                                                                app.dialog.alert('این تصویر حذف شد.', 'تایید');
                                                            }
                                                        });
                                                    } else {
                                                        app.dialog.alert('خطایی رخ داده است.', 'خطا');
                                                    }
                                                });
                                            });
                                        });
                                    };

                                    remove_listener();
                                    $$('.img-add').off('change').on('change', function (e) {
                                        let item = $$(this);
                                        app.dialog.progress("منتظر باشید.");
                                        if (item[0].files.length === 1) {
                                            let file = item[0].files[0];
                                            let reader = new FileReader();
                                            reader.addEventListener("load", function () {
                                                update_image(item.attr('data-id'), reader.result, file.name, function (result, id) {
                                                    app.dialog.close();
                                                    setTimeout(function () {
                                                        app.dialog.alert(result.message, 'کاشان کارت');
                                                        let content = $('div.content-image-area-' + result.shop_id);
                                                        let $slide = slide({
                                                            imgSrc: result.src,
                                                            ID: result.id
                                                        });
                                                        content.prepend($slide);
                                                        remove_listener();
                                                    }, 500);
                                                });
                                            }, false);
                                            if (file) {
                                                reader.readAsDataURL(file);
                                            }
                                        }
                                    });


                                });
                            });
                    }
                });
        }
    });


}(jQuery));

