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

import 'package:provider/provider.dart';
import 'package:twong/providers/home.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 getIndex() async {
    var resp = await Request.get('index');
    var data = Home.fromJson(resp);
    Provider.of<HomeModel>(Cache.context, listen: false).update(data);
    return data;
  }
  // 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);
    return _processToken(resp);
  }
  // auto login
  Future<UserInfo> autoLogin() async {
    if(Cache.account?.account != null && Cache.account?.password != null) {
      Log.i("begin auto login...");
      return login(account: Cache.account.account, password: Cache.account.password);
    }
    return null;
  }
  // request verify code
  Future verify() async {
    var resp = await Request.get("verify_code");
    var key = resp["key"];
    resp = await Request.post("register/verify");

  }
  // register account
  Future<UserInfo> register(String account, String code, String password,
      {String spread}) async
  {
    var params = {
      "account": account,
      "password": password,
      "captcha": code,
      "spread": spread
    };
    var resp = await Request.post("register", params: params);
    return _processToken(resp);
  }
  // login with sms
  Future smsLogin(String account, String code) async {
    var params = {
      "account": account,
      "captcha": code,
    };
    var resp = await Request.post("login/mobile", params: params);
    return _processToken(resp);
  }
  Future<UserInfo> _processToken(dynamic resp) async {
    if(resp == null) return null;

    var token = Token.fromJson(resp);
    Cache.updateToken(token);
    return 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;
  }
}