/**
 * Author: Damodar Lohani
 * profile: https://github.com/lohanidamodar
  */
import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:naim/classes/appdata.dart';
import 'dart:math';

import 'package:naim/classes/assets.dart';
import 'package:naim/widgets/broadcastbubble.dart';

import '../classes/Auth.dart';
import '../classes/message.dart';
import '../main.dart';

class ViewBroadcastPage extends StatefulWidget {
  @override
  _ViewBroadcastState createState() => _ViewBroadcastState();
  ViewBroadcastPage();
}

class _ViewBroadcastState extends State<ViewBroadcastPage> with RouteAware {
  String? text;
  TextEditingController? _controller;
  StreamSubscription? loginSubscription;
  List<String> avatarsx = [];
  List<dynamic> messages = [];
  final rand = Random();

  @override
  void initState() {
    super.initState();

    _controller = TextEditingController();

    loadMessages();
    main();
  }

  @override
  void didPopNext() {
    appData.currentchat = {};
  }

  @override
  void didPush() {}

  @override
  void dispose() {
    if (loginSubscription != null) {
      loginSubscription!.cancel();
    }
    routeObserver.unsubscribe(this);
    appData.currentchat = {};

    super.dispose();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    routeObserver.subscribe(this, ModalRoute.of(context) as PageRoute);
  }

  main() {
    loginSubscription = appData.eventBus!.on().listen((event) {},
        onError: (e) {
          print(e.toString());
        },
        onDone: () => print("doe with bus"));
  }

  @override
  Widget build(BuildContext context) {
    appData.context = context;
    return Scaffold(
      appBar: AppBar(
        foregroundColor: appColors.armyColor(context),
        leading: IconButton(
          onPressed: () {
            Navigator.of(context).pop();
          },
          icon: Icon(
            Icons.arrow_back,
            color: appColors.armyColor(context),
          ),
        ),
        backgroundColor: appColors.backgroundColor(context),
        title: Row(
          children: [
            const CircleAvatar(
              backgroundImage: AssetImage(
                appLogo,
              ),
              radius: 20.0,
            ),
            const SizedBox(width: 4),
            Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Text(
                  "BROADCASTS",
                  style: TextStyle(
                      color: appColors.textColor(context),
                      fontSize: 16,
                      fontWeight: FontWeight.bold),
                ),
              ],
            ),
          ],
        ),
      ),
      body: SafeArea(
        child: Column(
          children: <Widget>[
            Expanded(
              child: Container(
                decoration: BoxDecoration(
                  image: DecorationImage(
                    fit: BoxFit.cover,
                    colorFilter: ColorFilter.mode(
                        appColors.backgroundColor(context), BlendMode.multiply),
                    image: const AssetImage(camobkimg),
                  ),
                ),
                child: ListView.separated(
                  physics: BouncingScrollPhysics(),
                  separatorBuilder: (context, index) {
                    return const SizedBox(height: 10.0);
                  },
                  reverse: false,
                  itemCount: messages.length,
                  itemBuilder: (BuildContext context, int index) {
                    print("print ss");
                    print(messages[index]);
                    var u = NAUsers.fromJson(messages[index]);
                    print("it got here ==== == ");

                    return BroadcastBubble(messages[index], u);
                  },
                ),
              ),
            ),
            _buildBottomBar(context),
          ],
        ),
      ),
    );
  }

  Container _buildBottomBar(BuildContext context) {
    return Container(
        decoration: BoxDecoration(
          color: appColors.backgroundColor(context),
        ),
        padding: const EdgeInsets.symmetric(
          vertical: 8.0,
          horizontal: 20.0,
        ));
  }

  loadMessages() async {
    try {
      var dio = Dio();
      dio.options.baseUrl = appApi;
      var formData = {"token": appData.dbUser['token']};

      var response = await dio.post(
        "getbroadcast",
        data: formData,
        options: Options(
          method: 'POST',
          responseType: ResponseType.plain,
          headers: {
            HttpHeaders.contentLengthHeader:
                formData.length, // set content-length
          },
        ),
      );
      // print(response.data);
      //print("respnse data ======= ==");
      var data = json.decode(response.data);
      if (data["result"] != null) {
        if (data["result"] == "success") {
          var x = data["data"];

          setState(() {
            print("message count: ${messages.length}");
            messages = x;
            print("messagex count: ${messages.length}");
          });
        } else {
          return {"result": false, "msg": data["data"]["message"]};
        }
      }
    } catch (e) {
      print("Error: " + e.toString());
      return {"result": false, "msg": e.toString()};
    }
    return {"result": false, "msg": "Something went wrong"};
  }
}
