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(page, count);
    getUnreadMessage(0, likeUnreadMessageLive);
    getUnreadMessage(1, followUnreadMessageLive);
    getLatestMessage();
  }


  getMyMessage(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(error, "${error.toString()}");
    });
  }

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

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

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