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

export default class Categories {
    
        @observable categoryList = [];
        @observable selectedCategory = '';
        @observable categoryListLoading = false;
        @observable detailCategoryLoading = false;
        @observable postCategoryLoading = false;
        @observable categoryId = '';
        @observable delCategoryLoading = false;
        @observable putCategoryLoading = false;
        @observable isSearching = false;
        @observable dataFiltered = [];
        @observable categoryData = {
            id: '',
            name: ''
        };

        @observable currentPage = 1;
        @observable maxPage;
        @observable dataPerPage = 30;

        constructor(context) {
            this.http = context.http;
            this.context = context;
        }
    
        @action
        getCategoryList(){
            this.categoryListLoading = true;
            return this.http.get(`categories`).then(res => {
                this.categoryList = res.data;
                this.categoryListLoading = false;
            });
        }

        @action
        getCategoryDetail(id){
            this.categoryId = id;
            this.detailCategoryLoading = true;
            return this.http.get(`categories/${id}`).then(detail => {
                this.categoryData = detail[0];
                this.detailCategoryLoading = false;
            })
        }
    
        @computed
        get isCategoryEmpty() {
            if(this.categoryList.length > 0) {
                return false;
            }
            return true;
        }  
        
    
        @action
        postCategory(data){
            this.postCategoryLoading = true;
            return this.http.post('categories', data).then(res => {
                this.postCategoryLoading = false;
                this.getCategoryList();
                return res;
            })
        }
    
        @action
        putCategory(id,data){
            delete data.total_items;
            this.putCategoryLoading = true;
            return this.http.put(`categories/${id}`, data).then(res => {
                this.getCategoryList();
                return res;
            });
        }
    
        @action
        deleteCategory(id){
            this.categoryId = id;
            this.delCategoryLoading = true;
            return this.http.delete(`categories/${id}`).then(res => {
                this.delCategoryLoading = false;
                // console.log(detail[0]);
                this.getCategoryList();
                return res;
            })
        }

        filterData = (query) => {
            return this.categoryList.filter((data) => data.name.toLowerCase().indexOf(query) > -1);
          }

          @action
          search(text) {
            console.log(this.categoryList);
            this.dataFiltered = this.filterData(text);
          }
    }
