
export 'user.dart';
export 'order.dart';

import '../utils/index.dart';
import '../models/index.dart';

class Network {
  static Network _inst = new Network();
  static Network get inst => _inst;
  // get home page data
  Future<Home> getIndex({dynamic data}) async {
    var resp = await Request.get('index');
    return Home.fromJson(resp);
  }
  // user login
  Future<UserInfo> login({String account, String password, String code}) async {
    var params = {
      "code": code,
      "account": account,
      "password": password,
    };
    var resp = await Request.post("login", params: params);
    var token = Token.fromJson(resp);
    Cache.updateToken(token);
    return await getUserInfo();
  }
  // get user info
  Future<UserInfo> getUserInfo() async {
    var resp = await Request.get('userinfo');

    var info = UserInfo.fromJson(resp);
    Cache.updateUserInfo(info);
    return info;
  }
  // get user
  Future<User> getUser() async {
    var resp = await Request.get('user');

    var info = User.fromJson(resp);
    Cache.updateUser(info);
    return info;
  }
  // get product detail info
  Future<Details> getDetail({dynamic data}) async {
    return Details.fromJson(await Request.get("product/detail/" + data.toString()));
  }
  // search products with keyword
  Future<List<Product>> search(String keyword, {dynamic page = "1", dynamic limit = "20"}) async {
    var resp = await Request.get("products?page=$page&limit=$limit&keyword=$keyword");
    List<Product> list = List<Product>();
    var products = resp as List;
    for(var item in products) {
      list.add(Product.fromJson(item));
    }
    return list;
  }
}