import { observable, action, computed } from 'mobx';

export default class Notification {
    
        @observable list = [];
        @observable selected = {};
        @observable istLoading = false;
        @observable isSearching = false;
        @observable filtered = [];
        @observable unread_notif = 0;
        constructor(context) {
            this.http = context.http;
            this.context = context;
        }
    
        @action
        getList(){
            this.isLoading = true;
            return this.http.get("notifications")
            .then(res => {
              console.log(res.data, 'ini res')
              this.list = res.data;
              this.unread_notif = res.unread_notif;
              this.isLoading = false;
            })
            .catch(err => {
              this.isLoading = false;
              throw err;
            })
        }

        @action
        readAll(){
          return this.http.put("notifications/read_all",{}).then(res=>{
            this.unread_notif = 0;
          })
        }

        @action
        getDetail(id){
            this.isLoading = true;
            return this.http.get(`notifications/${id}`)
            .then(res => {
              this.selected = res;
              this.isLoading = false;
            })
            .catch(err => {
              this.isLoading = false;
              throw err;
            })
        } 
    
        @action
        post(data){
            this.isLoading = true;
            return this.http.post("notifications", data)
              .then(res => {
                this.isLoading = false;
                this.getList();
                return res;
              })
              .catch(err => {
                this.isLoading = false;
                throw err;
              })
        }
    
        @action
        put(id,data){
            this.isLoading = true;
            return this.http.put(`notifications/${id}`, data)
              .then(res => {
                this.isLoading = false;
                this.getList();
                return res;
              })
              .catch(err => {
                this.isLoading = false;
                throw err;
              })
        }
    
        @action
        delete(id){
            this.isLoading = true;
            return this.http.delete(`notifications/${id}`)
              .then(res => {
                this.isLoading = false;
                this.getList();
                return res;
              })
              .catch(err => {
                this.isLoading = false;
                throw err;
              })
        }

        filterItems = (query) => {
          return this.list.filter((el) =>
            el.id.toLowerCase().indexOf(query.toLowerCase()) > -1 
          );
        }

        @action
        search(text){
          this.filtered = this.filterItems(text);
        }
    }
