import 'package:flutter/material.dart';
import 'package:gmalpha_flutter/NewMessageModel/service/MessageRepository.dart';
import 'package:gmalpha_flutter/NewMessageModel/service/remote/entity/LatestMessageEntity.dart';
import 'package:gmalpha_flutter/NewMessageModel/service/remote/entity/UnreadMessageEntity.dart';
import 'package:gmalpha_flutter/NewMessageModel/service/remote/entity/MyMessageEntity.dart';
import 'package:gmalpha_flutter/commonModel/live/BaseModel.dart';
import 'package:gmalpha_flutter/commonModel/live/LiveData.dart';
import 'package:gmalpha_flutter/commonModel/toast/toast.dart';

class MessageModel extends BaseModel {
  final int page;
  final int count;
  LiveData<MyMessageEntity> myMessageLive = new LiveData();
  LiveData<UnreadMessageEntity> likeUnreadMessageLive = new LiveData();
  LiveData<UnreadMessageEntity> followUnreadMessageLive = new LiveData();
  LiveData<LatestMessageEntity> latestMessageLive = new LiveData();
  MyMessageEntity myMessageList;

  MessageModel(this.page, this.count);

  init(BuildContext context) {
    getMyMessage(context, page, count);
    getUnreadMessage(context, 0, likeUnreadMessageLive);
    getUnreadMessage(context, 1, followUnreadMessageLive);
    getLatestMessage(context);
  }

  getMyMessage(BuildContext context, page, count, [callback]) {
    MessageRepository.getInstance().getMyMessage(page, count).listen((value) {
      if (value != null) {
        if (page > 1) {
          myMessageList.data?.addAll(value.data);
        } else {
          myMessageList = value;
        }
        if (callback != null) callback(value);
        myMessageLive.notifyView(myMessageList);
      }
    }).onError((error) {
      Toast.show(context, "${error.toString()}");
    });
  }

  getUnreadMessage(BuildContext context, type, dataLive) {
    MessageRepository.getInstance().getUnreadMessage(type).listen((value) {
      if (value != null) {
        dataLive.notifyView(value);
      }
    }).onError((error) {
      Toast.show(context, "${error.toString()}");
    });
  }

  getLatestMessage(BuildContext context) {
    MessageRepository.getInstance().getLatestMessage().listen((value) {
      if (value != null) {
        latestMessageLive.notifyView(value);
      }
    }).onError((error) {
      Toast.show(context, "${error.toString()}");
    });
  }

  @override
  void dispose() {
    myMessageLive.dispost();
    likeUnreadMessageLive.dispost();
    followUnreadMessageLive.dispost();
    latestMessageLive.dispost();
  }
}
