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

export default class StoreList {
    
        @observable list = [];
        @observable selected = {};
        @observable istLoading = false;
        @observable isSearching = false;
        @observable filtered = [];

        constructor(context) {
            this.http = context.http;
            this.context = context;
        }
    
        @action
        getList(){
            this.isLoading = true;
            return this.http.get("stores")
            .then(res => {
              this.list = res;
              this.isLoading = false;
            })
            .catch(err => {
              this.isLoading = false;
              throw err;
            })
        }

        @action
        getDetail(id){
            this.isLoading = true;
            return this.http.get(`stores/${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("stores", 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(`stores/${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(`stores/${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.name.toLowerCase().indexOf(query.toLowerCase()) > -1 
          );
        }

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