/*
* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class PicBean {
  String name;
  int id;
  PicBean(this.name, this.id);
}

List<PicBean> pics = [
  PicBean("1.png", 0),
  PicBean("2.jpeg", 0),
  PicBean("3.jpeg", 0),
  PicBean("4.jpg", 0),
  PicBean("6.jpg", 0),
];

class PicturePage1 extends StatefulWidget {
  const PicturePage1({super.key});
  @override
  State<PicturePage1> createState() => _PicturePageState();
}

class _PicturePageState extends State<PicturePage1> {
  final MethodChannel _channel = const MethodChannel('PictureChannel1');
  late Future<void> _initFuture;
  int _starTextureId = -1;

  @override
  void initState() {
    super.initState();
    _initFuture = _initializeTextures();
  }

  Future<void> _initializeTextures() async {
    for (PicBean pic in pics) {
      try {
        int id = await _channel.invokeMethod("registerTexture", {'pic': pic.name});
        pic.id = id;
      } catch (e) {
        print("Error registering texture for ${pic.name}: $e");
      }
    }

    try {
      _starTextureId = await _channel.invokeMethod("registerStarTexture");
    } catch (e) {
      print("Error registering star texture: $e");
    }
  }

  @override
  void dispose() {
    _unregisterTextures();
    super.dispose();
  }

  void _unregisterTextures() async {
    for (PicBean pic in pics) {
      if (pic.id >= 0) {
        await _channel.invokeMethod('unregisterTexture', {'textureId': pic.id});
      }
    }
    if (_starTextureId >= 0) {
      await _channel.invokeMethod('unregisterTexture', {'textureId': _starTextureId});
    }
  }

  Widget _buildTextureWidget(PicBean picBean) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        SizedBox(
          width: 300,
          height: 300,
          child: picBean.id >= 0
              ? Texture(textureId: picBean.id)
              : const Center(child: CircularProgressIndicator()),
        ),
        const SizedBox(height: 10),
        Text(picBean.name),
      ],
    );
  }

  Widget _buildStarTextureWidget() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        SizedBox(
          width: 300,
          height: 300,
          child: _starTextureId >= 0
              ? Texture(textureId: _starTextureId)
              : const Center(child: CircularProgressIndicator()),
        ),
        const SizedBox(height: 10),
        const Text("Star"),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("daex_texture")),
      body: FutureBuilder(
        future: _initFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return ListView.builder(
              itemCount: pics.length + 1,
              itemBuilder: (context, index) {
                if (index < pics.length) {
                  return _buildTextureWidget(pics[index]);
                } else {
                  return _buildStarTextureWidget();
                }
              },
            );
          } else if (snapshot.hasError) {
            return Center(child: Text("Error: ${snapshot.error}"));
          } else {
            return const Center(child: CircularProgressIndicator());
          }
        },
      ),
    );
  }
}