import {Injectable} from '@angular/core';
import {LocalNotifications} from '@ionic-native/local-notifications/ngx';
import {Api} from './api';
import {environment} from '../../environments/environment';

declare var mqtt: any;

@Injectable()
export class Mqtt {
    constructor(private localNotifications: LocalNotifications, private api: Api) {
    }

    client;
    topic;
    msg;
    private options = {
        keepalive: 10,
        clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
        protocolId: 'MQTT',
        protocolVersion: 4,
        clean: false,
        connectTimeout: 60000,
        username: 'pasture',
        password: 'Pasture37774020',
    };

    getUserInfo() {
        this.api.user.getSelfInfo(['', (data) => {
            if (data.userName) {
                this.initMqtt(data.userName);
            } else {
                this.api.presentMsgToast('报警消息订阅失败');
            }
        }]);
    }

    public initMqtt(name) {
        this.client = mqtt.connect('ws://' + environment.mqttUrl + ':8083/mqtt', this.options);
        this.topic = 'Pasture/' + name + '/Alarm';

        this.client.on('connect', () => {
            this.msg = 'mqtt连接成功';
            this.client.subscribe(this.topic);
            this.client.on('message', (a, b) => {
                const obj = JSON.parse(b.toString());
                this.localNotifications.schedule([{
                    title: '牧场报警',
                    text: this.api.formatTime('yyyy-MM-dd hh:mm:ss', new Date(obj.alarmTime)) + '  ' + obj.description,
                    sound: 'file://beep.caf',
                    icon: 'https://witcloud-oss.oss-cn-shanghai.aliyuncs.com/mysqldump/pasture.png',
                    foreground: true,
                    silent: false,
                    vibrate: true,
                    led: '#ff0000'
                }]);
                this.api.presentMsgToast(
                    this.api.formatTime('yyyy-MM-dd hh:mm:ss', new Date(obj.alarmTime)) + '  ' + obj.description, 'top', 5000
                );
            });
        });
    }

    public endMqtt() {
        this.client.unsubscribe(this.topic);
        this.client.disconnect();
    }
}
