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

export default class Agent {
  
  @observable agentList = [];
  @observable selectedAgent = {};
  @observable isLoading = false;
  @observable agentId = '';
  @observable agentData = {
    name : '',
    phone_number : '',
    email : '',
    address : '',
    id: '',
    created_at: '',
    user_id:'',
    id_tax_number : '',
    id_type : '',
    id_number : '',
    id_photo : '',
    passport_number: '',
    passport_photo : '',
    error_email : '',
  };
  @observable orders = [];
  
  
  constructor(context) {
    this.http = context.http;
    this.context = context;
  }
  
  
  // @action
  // getAgentList(){
  //     this.isLoading = true;
  //     return this.http.get(`agents`).then(res => {
  //         this.agentList = res;
  //         this.isLoading = false;
  //     });
  // }
  @action
  getAgentList() {
    this.isLoading = true;
    return this.http.get("agents")
      .then(res => {
        this.agentList = res;
        this.isLoading = false;
      })
      .catch(err => {
        this.isLoading = false;
        throw err;
      })
  }
  
  @computed
  get isAgentEmpty() {
    if(this.agentList.length > 0) {
      return false;
    }
    return true;
  }  
  
  @action
  getDetail(id){
    this.isLoading = true;
    this.agentId = id;
    return this.http.get(`agents/${id}`).then(detail => {
      this.agentData = detail[0];
      this.isLoading = false;
    })
  }
  
  
  
  @action
  post(){
    this.isLoading = true;
    this.http.post('agents', this.agentData).then(res => {
      this.isLoading = false;
      this.getAgentList();
      return res;
    })
  }
  
  @action
  put(id){
    this.isLoading = true;
    this.http.put(`agents/${id}`, this.agentData).then(res => {
      this.isLoading = false;
      this.getAgentList();
      return res;
    });
  }
  
  @action
  getOrder(id=this.selectedAgent.id) {
    this.isLoading = true;
    return this.http.get(`agents/${id}/orders`)
    .then(res => {
      this.orders = res;
      this.isLoading = false;
    })
    .catch(err => {
      this.isLoading = false;
      throw err;
    })
  }
  
  @action
  editData(id,data){
    this.isLoading = true;
    this.http.put(`agents/${id}`, data).then(res => {
      this.isLoading = false;
      this.getDetail(id);
      return res;
    });
  }
  
  @action
  delete(id){
    this.agentId = id;
    this.isLoading = true;
    this.http.delete(`agentData/${id}`).then(res => {
      this.isLoading = false;
      // console.log(detail[0]);
      this.getAgentList();
      return res;
    })
  }
}
