import 'package:dio/dio.dart';

import '../../contracts/trakt/trakt_token.dart';
import '../../contracts/trakt/trakt_user.dart';
import 'trakt_credentials.dart';


class TraktRestApi {
  TraktRestApi(this._dio) {
    _dio.options.baseUrl = _dio.options.baseUrl.isEmpty
        ? TraktCredentials.apiBaseUrl
        : _dio.options.baseUrl;
  }

  final Dio _dio;


  Future<TraktToken> exchangeToken(Map<String, dynamic> body) async {
    final response = await _dio.post<dynamic>('/oauth/token', data: body);
    return TraktToken.fromJson(_jsonObject(response.data));
  }


  Future<TraktUserSettings> getUserSettings(String authorization) async {
    final response = await _dio.get<dynamic>(
      '/users/settings',
      options: Options(headers: {'Authorization': authorization}),
    );
    return TraktUserSettings.fromJson(_jsonObject(response.data));
  }

  Map<String, dynamic> _jsonObject(dynamic data) {
    if (data is Map<String, dynamic>) return data;
    if (data is Map) return Map<String, dynamic>.from(data);
    throw FormatException(
      'Trakt response is not a JSON object: ${data.runtimeType}',
    );
  }
}


class TraktHeaderInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    options.headers['trakt-api-key'] = TraktCredentials.clientId;
    options.headers['trakt-api-version'] = TraktCredentials.apiVersion;
    options.headers['Content-Type'] = 'application/json';
    handler.next(options);
  }
}
