import 'dart:io';

import 'package:cinema/common/dio_module.dart';
import 'package:cinema/common/domain/serializers.dart';
import 'package:cinema/common/lvgl_image_converter.dart';
import 'package:cinema/feature/poster/data/repositories/image_loader.dart';
import 'package:cinema/feature/poster/domain/movie.dart';
import 'package:cinema/feature/poster/domain/tmdb_trending_response.dart';
import 'package:dio/dio.dart';
import 'package:injectable/injectable.dart';

@Injectable(as: ImageLoader)
class TmDBImageLoader implements ImageLoader {
  final Dio api;
  final Dio images;
  final LvglImageConverter lvglConverter;
  final String imageBaseUrl = 'https://image.tmdb.org/t/p/w500';

  TmDBImageLoader(
    @Named(dioAPI) this.api,
    @Named(dioIMAGES) this.images,
    this.lvglConverter,
  );

  @override
  Future<List<Movie>> getMovies({String? language = 'de'}) async {
    final response = await api.get('/trending/movie/week?language=$language');
    if (response.data != null) {
      final data = serializers.deserializeWith(TmdbTrendingResponse.serializer, response.data);
      return data?.results
              .map(
                (movie) => Movie(
                  (b) => b
                    ..id = movie.id
                    ..title = movie.title
                    ..poster = movie.posterPath
                    ..backdrop = movie.backdropPath
                    ..release = movie.releaseDate
                    ..video = movie.video,
                ),
              )
              .toList() ??
          [];
    }
    return [];
  }

  @override
  Future<bool> downloadImages(Movie movie) async {
    await _downloadImage(movie.poster, "cache/movie/${movie.id}/poster.jpeg");
    await _downloadImage(movie.backdrop, "cache/movie/${movie.id}/backdrop.jpeg");
    return true;
  }

  Future<bool> _downloadImage(String url, String filename) async {
    final file = File(filename);
    if (await file.exists()) {
      return false;
    }

    await file.parent.create(recursive: true);
    final response = await images.get(url, options: Options(responseType: ResponseType.bytes));
    await file.writeAsBytes(response.data);

    final binFilename = filename.replaceAll('.jpeg', '.bin');
    await lvglConverter.convertPngToBin(filename, binFilename);

    return true;
  }
}
