/**
 * Created by xiaoqiang on 2018/7/27.
 */
var Message = /** @class */ (function () {
    function Message(cmd, email, uid, extra, bin) {
        this.mid = String((new Date()).getTime());
        this.uid = uid;
        this.command = cmd;
        this.from = 'panel';
        this.email = email;
        this.extra = extra;
        this.binary = bin;
    }
    Message.prototype.toJSON = function () {
        var obj = {
            mid: this.mid,
            command: this.command,
            from: this.from,
            email: this.email,
            uid: this.uid
        };
        if (this.extra) {
            obj['extra'] = this.extra;
        }
        return obj;
    };
    Message.fromJSON = function (json) {
        var cmd = (json['command']) ? json['command'] : '';
        var from = (json['from']) ? json['from'] : '';
        var email = (json['email']) ? json['email'] : '';
        var uid = (json['uid']) ? json['uid'] : '';
        var extra = (json['extra']) ? JSON.stringify(json['extra']) : '';
        var msg = new Message(cmd, email, uid, extra);
        msg.from = from;
        msg.mid = json['mid'];
        return msg;
    };
    return Message;
}());
Vue.component('preview', {
    template: '#preview',
    props: ['user'],
    data: function () {
        return {
            name: 'preview component',
            ws: null,
            extraShow: true,
            toolShow: 0,
            localIP: LOCAL_IP,
            deviceIP: '',
            refreshing: false,
            status: 0,
            tryTimes: 0,
            trialLeft: 0,
            version: VERSION,
            devices: [],
            showUserGuide: false,
            update: 0,
            isExpired: false,
            updateInfo: {
                version: '0',
                url: ''
            },
            errorCode: 0
        };
    },
    methods: {
        toolAction: function (index) {
            if (this.toolShow == index) {
                this.toolShow = 0;
                return;
            }
            this.toolShow = index;
        },
        onAddIp: function () {
            console.log('on add ip: ' + this.deviceIP);
            if (this.deviceIP.match(/^((25[0-5]|2[0-4]\d|[01]?\d\d?)($|(?!\.$)\.)){4}$/)) {
                bridge.call('add_device_ip', { ip: this.deviceIP }, function () { });
                /*
                let msg:Message = new Message('add_device_ip', this.user.email, this.user.uid, JSON.stringify({ip: this.deviceIP}));
                this.ws.send(Utils.parseSend(msg.toJSON()));
                */
            }
        },
        refreshUsb: function (type) {
            var _this = this;
            if (this.refreshing) {
                return;
            }
            this.refreshing = true;
            bridge.call('refresh_usb', { type: type }, function () { });
            /*
            let msg:Message = new Message('usb_refresh', this.user.email, this.user.uid, JSON.stringify({type: type}));
            this.ws.send(Utils.parseSend(msg.toJSON()));
            */
            setTimeout(function () {
                _this.refreshing = false;
            }, 3000);
        },
        openBrowser: function () {
            bridge.openURL("http://" + this.localIP + ":42211/web.html");
        },
        actionQRCode: function () {
            new QRCode("qrcode", {
                text: 'http://' + this.localIP + ':53330/index?uid=' + this.user.uid + '&email=' + this.user.email + '&hostIp=' + this.localIP,
                width: 120,
                height: 120,
                colorDark: "#000000",
                colorLight: "#ffffff",
                correctLevel: QRCode.CorrectLevel.H
            });
        },
        countTrialLeft: function () {
            if (this.user.licence != '') {
                this.trialLeft = -1;
                return;
            }
            var start = this.user.trial_start * 1000;
            var now = (new Date()).getTime();
            if (now - start > 15 * 24 * 3600 * 1000) { // 试用期15天
                this.trialLeft = 0;
            }
            else {
                this.trialLeft = Math.round((start + 15 * 24 * 3600 * 1000 - now) / (24 * 3600 * 1000));
            }
        },
        onMessage: function (messages) {
            var _this = this;
            messages.forEach(function (message) {
                console.log("on message command[" + message.command + "]");
                switch (message.command) {
                    case 'document_list':
                        break;
                    case 'image':
                        if (message.binary) {
                            var extra = JSON.parse(JSON.parse(message.extra));
                            var url = "data:image/jpg;base64," + Utils.arrayBufferToBase64(message.binary);
                            $('#preview-image').attr('src', url);
                            _this.renderImage(extra);
                        }
                        break;
                    case 'connected_devices':
                        //console.log(`connected devices[${message.extra}]`);
                        _this.devices = [];
                        var items = JSON.parse(JSON.parse(message.extra));
                        items.forEach(function (obj) {
                            //let obj = JSON.parse(item);
                            if (obj.os < 2 || obj.os == 'IPHONE' || obj.os == 'ANDROID') {
                                _this.devices.push(obj);
                            }
                        });
                        break;
                    case 'trial_expire':
                        _this.isExpired = true;
                        break;
                    case 'account_invalid':
                        bridge.showToast(rb.UI_PREVIEW_ACCOUNT_INVALID);
                        _this.logout();
                        break;
                }
            });
        },
        renderImage: function (extra) {
            var width = parseInt(extra['width']);
            if (width < 500) {
                width = width * 3;
            }
            else if (width < 1000) {
                width = width * 1.5;
            }
            var w = document.documentElement.clientWidth;
            console.log("panel width[" + w + "], image width[" + width + "]");
            var val = (width > w) ? '100%' : 'auto';
            $('#preview-image').css('width', val);
        },
        buy: function () {
            bridge.openURL(rb.UI_USER_TEXT_6 + '?app=' + APP_NAME + '&token=' + this.user.token);
        },
        logout: function () {
            var _this = this;
            bridge.deleteFile('user.json').then(function () {
                return Store.clean();
            }).then(function () {
                _this.$emit('onlogout');
            });
        },
        checkUpdate: function () {
            var _this = this;
            if (Store.getValue('check_update') != null) {
                var timestamp = Store.getTimestamp('check_update');
                var now = (new Date()).getTime();
                if (now - timestamp < 24 * 3600 * 1000) {
                    return;
                }
            }
            Store.save('check_update', 1);
            bridge.checkUpdate(this.user.uid).then(function (result) {
                _this.update = result['update'];
                _this.updateInfo.version = result['version'];
                _this.updateInfo.url = result['download_url'];
            });
        },
        download: function () {
            bridge.openURL(this.updateInfo.url);
        },
        downloadItunes: function () {
            bridge.openURL('http://www.apple.com/itunes/download/');
        },
        connect: function () {
            var _this = this;
            console.log("connect to local webserver");
            this.ws = new WebSocket('ws://127.0.0.1:42200');
            this.ws.binaryType = 'arraybuffer';
            this.ws.onopen = function () {
                console.log('connected to local webserver');
                _this.status = 1;
                _this.tryTimes = 0;
                var msg = new Message('register', _this.user.email, _this.user.email, JSON.stringify({
                    deviceName: 'panel',
                    deviceType: 'web',
                    dpi: '320x577',
                    ip: '127.0.0.1',
                    mac: '127.0.0.1',
                    version: '1.0'
                }));
                _this.ws.send(Utils.parseSend(msg.toJSON()));
            };
            this.ws.onmessage = function (msgEvt) {
                var data = msgEvt.data;
                _this.onMessage(Utils.parseReceived(data));
            };
            this.ws.onerror = function (err) {
                console.log('connect to local host error, now try');
                _this.tryTimes++;
                if (_this.tryTimes > 6) {
                    _this.connectFail();
                    return;
                }
                setTimeout(_this.connect, 2000);
            };
        },
        connectFail: function () {
            this.status = 2;
        },
        help: function () {
            bridge.openURL(rb.UI_PREVIEW_HELP_LINK + '?errorCode=' + this.errorCode);
        },
    },
    created: function () {
        this.localIP = LOCAL_IP;
        this.deviceIP = this.localIP.replace(/\.\d+$/, '.');
        this.connect();
    },
    mounted: function () {
        var h = document.documentElement.clientHeight;
        console.log('preview component created, height: ' + h);
        h = h + 20;
        $('#wrapper').css('height', h + 'px');
        $('.preview-inner').css('height', h + 'px').css('lineHeight', h + 'px');
        this.actionQRCode();
        this.countTrialLeft();
        if (Store.getValue('show_panel_guide') == null) {
            this.showUserGuide = true;
            Store.save('show_panel_guide', 1);
        }
        this.checkUpdate();
        window.initResourceBundle();
    }
});
